Skip to content

A truly modular keyboard

C

app: protocol extensions, macros, profile library and undo history

Nathana5a45cfd10a6
diff --git a/app/renderer/hid.js b/app/renderer/hid.js
index 0c47466..c9f9a74 100644
--- a/app/renderer/hid.js
+++ b/app/renderer/hid.js
@@ -91,7 +91,77 @@
return { mods, usage: k.usage };
}
- const api = { KEYS, MODS, CONSUMER, byUsage, comboLabel, consumerLabel, fromEvent, modName };
+ // Characters on a US layout -> [mods, usage] taps, for typing text with a macro.
+ const SHIFTED = { '!': '1', '@': '2', '#': '3', $: '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0',
+ _: '-', '+': '=', '{': '[', '}': ']', '|': '\\', ':': ';', '"': "'", '~': '`', '<': ',', '>': '.', '?': '/' };
+ const PLAIN = { '-': 0x2d, '=': 0x2e, '[': 0x2f, ']': 0x30, '\\': 0x31, ';': 0x33, "'": 0x34, '`': 0x35,
+ ',': 0x36, '.': 0x37, '/': 0x38, ' ': 0x2c, '\n': 0x28, '\t': 0x2b };
+ function charToStep(ch) {
+ if (/[a-z]/.test(ch)) return [0, 0x04 + ch.charCodeAt(0) - 97];
+ if (/[A-Z]/.test(ch)) return [2, 0x04 + ch.charCodeAt(0) - 65];
+ if (/[1-9]/.test(ch)) return [0, 0x1e + Number(ch) - 1];
+ if (ch === '0') return [0, 0x27];
+ if (ch in PLAIN) return [0, PLAIN[ch]];
+ if (ch in SHIFTED) { const base = charToStep(SHIFTED[ch]); return base && [2, base[1]]; }
+ return null;
+ }
+ // Returns { steps, skipped } where skipped lists characters with no US-layout key.
+ function textToSteps(text) {
+ const steps = [];
+ const skipped = [];
+ for (const ch of text) {
+ const st = charToStep(ch);
+ if (st) steps.push(st); else skipped.push(ch);
+ }
+ return { steps, skipped };
+ }
+
+ // Label for one macro step, and for a whole sequence ("Ctrl+C, Ctrl+V").
+ const stepLabel = ([mods, key], mac) => comboLabel(mods, key, mac);
+ function macroLabel(steps, mac) {
+ // Runs of plain or shifted printable characters read better as text.
+ const out = [];
+ let text = '';
+ const flush = () => { if (text) out.push(`"${text}"`); text = ''; };
+ for (const st of steps) {
+ const ch = stepChar(st);
+ if (ch != null) text += ch;
+ else { flush(); out.push(stepLabel(st, mac)); }
+ }
+ flush();
+ return out.join(', ');
+ }
+ const charByStep = new Map();
+ for (let c = 32; c < 127; c++) {
+ const ch = String.fromCharCode(c);
+ const st = charToStep(ch);
+ if (st && !charByStep.has(st.join(':'))) charByStep.set(st.join(':'), ch);
+ }
+ const stepChar = (st) => charByStep.get(st.join(':')) ?? null;
+
+ // Fuzzy-ish search over keys and media keys for the Assign dialog.
+ // Returns [{kind: 'k'|'c', usage, label}] best match first.
+ function search(query) {
+ const q = query.trim().toLowerCase();
+ const all = [
+ ...KEYS.map((k) => ({ kind: 'k', usage: k.usage, label: k.label, hay: `${k.label} ${k.code}`.toLowerCase() })),
+ ...CONSUMER.map((c) => ({ kind: 'c', usage: c.usage, label: c.label, hay: `${c.label} ${c.code} media`.toLowerCase() })),
+ ];
+ if (!q) return all.map(({ hay, ...r }) => r);
+ const scored = [];
+ for (const r of all) {
+ const label = r.label.toLowerCase();
+ let score = -1;
+ if (label === q) score = 0;
+ else if (label.startsWith(q)) score = 1;
+ else if (r.hay.includes(q)) score = 2;
+ else if (q.split(/\s+/).every((w) => r.hay.includes(w))) score = 3;
+ if (score >= 0) scored.push([score, r]);
+ }
+ return scored.sort((a, b) => a[0] - b[0]).map(([, { hay, ...r }]) => r);
+ }
+
+ const api = { KEYS, MODS, CONSUMER, byUsage, comboLabel, consumerLabel, fromEvent, modName, textToSteps, macroLabel, stepLabel, search };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.Hid = api;
})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/app/renderer/profiles.js b/app/renderer/profiles.js
index 195ed07..5704218 100644
--- a/app/renderer/profiles.js
+++ b/app/renderer/profiles.js
@@ -1,39 +1,105 @@
-// Keymap profiles: { id, name, keys: { <UID>: { mods, key, name? } } }.
-// The store is { active: <id>, profiles: [...] } and is saved as JSON by main.js.
+// Keymap profiles and the app's saved state.
+//
+// store = { active, profiles: [profile], settings, stats }
+// profile = { id, name, apps: [app name], keys: { <UID>: entry } }
+// entry: one main action, plus an optional name and hold action:
+// { mods, key } keyboard key or shortcut
+// { consumer } media key (HID consumer page)
+// { macro: [[mods, key], ...] } sequence of taps
+// { host: { type, value } } run by the app: url | app | cmd | next-profile | profile
+// name: 'Mute mic' optional label
+// hold: { mods, key, ms } optional action while held (firmware tap/hold)
(function (root) {
const FORMAT = 'keyword-profile';
+ const LIBRARY_FORMAT = 'keyword-profile-library';
+ const HOST_TYPES = ['url', 'app', 'cmd', 'next-profile', 'profile'];
+ const MAX_MACRO_STEPS = 16;
+
+ const DEFAULT_SETTINGS = {
+ theme: 'system', // system | light | dark
+ autoReconnect: true,
+ perApp: false, // switch profiles by frontmost app
+ notifications: false, // OS notification on connect/disconnect
+ closeToTray: false,
+ launchAtLogin: false,
+ lastConnection: null, // { kind: 'serial', usbVendorId, usbProductId } | { kind: 'ble', id, name }
+ };
const newId = () => Math.random().toString(36).slice(2, 10);
+ const byte = (n) => (Number(n) || 0) & 0xff;
- function newProfile(name, keys = {}) {
- return { id: newId(), name: name || 'Profile', keys: { ...keys } };
+ function newProfile(name, keys = {}, apps = []) {
+ return { id: newId(), name: name || 'Profile', apps: [...apps], keys: JSON.parse(JSON.stringify(keys)) };
+ }
+
+ function cleanEntry(m) {
+ if (!m || typeof m !== 'object') return null;
+ const entry = {};
+ if (m.host && HOST_TYPES.includes(m.host.type)) {
+ entry.host = { type: m.host.type, value: typeof m.host.value === 'string' ? m.host.value.slice(0, 1000) : '' };
+ } else if (Array.isArray(m.macro) && m.macro.length) {
+ entry.macro = m.macro.slice(0, MAX_MACRO_STEPS)
+ .filter((s) => Array.isArray(s) && s.length === 2)
+ .map(([mods, key]) => [byte(mods), byte(key)]);
+ } else {
+ const consumer = (Number(m.consumer) || 0) & 0xffff;
+ if (consumer) Object.assign(entry, { mods: 0, key: 0, consumer });
+ else Object.assign(entry, { mods: byte(m.mods), key: byte(m.key) });
+ }
+ if (m.hold && (m.hold.mods || m.hold.key)) {
+ entry.hold = { mods: byte(m.hold.mods), key: byte(m.hold.key), ms: Math.min(2000, Math.max(50, Number(m.hold.ms) || 200)) };
+ }
+ if (typeof m.name === 'string' && m.name.trim()) entry.name = m.name.trim().slice(0, 40);
+ return entry;
}
function cleanKeys(keys) {
const out = {};
if (!keys || typeof keys !== 'object') return out;
for (const [uid, m] of Object.entries(keys)) {
- if (!/^([0-9a-fA-F]{24}|[0-9a-fA-F]{8})$/.test(uid) || !m || typeof m !== 'object') continue;
- const consumer = (Number(m.consumer) || 0) & 0xffff;
- const entry = consumer ? { mods: 0, key: 0, consumer } : { mods: (Number(m.mods) || 0) & 0xff, key: (Number(m.key) || 0) & 0xff };
- if (typeof m.name === 'string' && m.name.trim()) entry.name = m.name.trim().slice(0, 40);
- out[uid.toUpperCase()] = entry;
+ if (!/^([0-9a-fA-F]{24}|[0-9a-fA-F]{8})$/.test(uid)) continue;
+ const entry = cleanEntry(m);
+ if (entry) out[uid.toUpperCase()] = entry;
}
return out;
}
+ const cleanApps = (apps) => (Array.isArray(apps) ? [...new Set(apps.filter((a) => typeof a === 'string' && a.trim()).map((a) => a.trim().slice(0, 80)))] : []);
+
+ // Does an entry do anything when pressed?
+ const isMapped = (m) => !!(m && (m.host || m.macro?.length || m.consumer || m.mods || m.key));
+
// What gets written by Export.
function exportProfile(p) {
- return JSON.stringify({ format: FORMAT, version: 1, name: p.name, keys: cleanKeys(p.keys) }, null, 2);
+ return JSON.stringify({ format: FORMAT, version: 1, name: p.name, apps: cleanApps(p.apps), keys: cleanKeys(p.keys) }, null, 2);
}
- // Parses an exported file. Throws with a readable message if it isn't one.
- function importProfile(text) {
+ // Every profile in one file.
+ function exportLibrary(profiles) {
+ return JSON.stringify({
+ format: LIBRARY_FORMAT, version: 1,
+ profiles: profiles.map((p) => ({ name: p.name, apps: cleanApps(p.apps), keys: cleanKeys(p.keys) })),
+ }, null, 2);
+ }
+
+ // Parses an exported profile or library. Throws with a readable message if it's neither.
+ // Always returns a list of new profiles.
+ function importProfiles(text) {
let data;
try { data = JSON.parse(text); } catch { throw new Error('Not a JSON file'); }
+ const one = (d, fallback) => newProfile(typeof d.name === 'string' && d.name.trim() ? d.name.trim() : fallback, cleanKeys(d.keys), cleanApps(d.apps));
+ if (data?.format === LIBRARY_FORMAT) {
+ if (data.version !== 1) throw new Error(`Unsupported library version ${data.version}`);
+ if (!Array.isArray(data.profiles)) throw new Error('Library has no profiles');
+ return data.profiles.filter((d) => d && typeof d === 'object').map((d) => one(d, 'Imported'));
+ }
if (!data || data.format !== FORMAT) throw new Error('Not a Keyword profile');
if (data.version !== 1) throw new Error(`Unsupported profile version ${data.version}`);
- return newProfile(typeof data.name === 'string' && data.name.trim() ? data.name.trim() : 'Imported', cleanKeys(data.keys));
+ return [one(data, 'Imported')];
+ }
+
+ function importProfile(text) {
+ return importProfiles(text)[0];
}
// Repairs a store loaded from disk so the UI can trust it.
@@ -42,15 +108,66 @@
? store.profiles.filter((p) => p && typeof p === 'object').map((p) => ({
id: typeof p.id === 'string' ? p.id : newId(),
name: typeof p.name === 'string' && p.name ? p.name : 'Profile',
+ apps: cleanApps(p.apps),
keys: cleanKeys(p.keys),
}))
: [];
if (!profiles.length) profiles.push(newProfile('Default'));
const active = profiles.some((p) => p.id === store?.active) ? store.active : profiles[0].id;
- return { active, profiles };
+ const settings = { ...DEFAULT_SETTINGS };
+ for (const k of Object.keys(DEFAULT_SETTINGS)) {
+ const v = store?.settings?.[k];
+ if (v !== undefined && (typeof v === typeof DEFAULT_SETTINGS[k] || DEFAULT_SETTINGS[k] === null)) settings[k] = v;
+ }
+ if (!['system', 'light', 'dark'].includes(settings.theme)) settings.theme = 'system';
+ const stats = {};
+ for (const [uid, n] of Object.entries(store?.stats || {})) if (Number.isFinite(n) && n > 0) stats[uid] = Math.floor(n);
+ return { active, profiles, settings, stats };
+ }
+
+ // Which profile should be active for a frontmost app, or null for "no rule".
+ function profileForApp(profiles, appName) {
+ if (!appName) return null;
+ const a = appName.toLowerCase();
+ return profiles.find((p) => p.apps.some((x) => x.toLowerCase() === a)) || null;
+ }
+
+ // Undo/redo over JSON snapshots of the parts the user edits.
+ class History {
+ constructor(limit = 100) {
+ this.limit = limit;
+ this.undoStack = [];
+ this.redoStack = [];
+ }
+ // Call before a change, with the state as it is now.
+ record(snapshot, label) {
+ this.undoStack.push({ snapshot: JSON.stringify(snapshot), label });
+ if (this.undoStack.length > this.limit) this.undoStack.shift();
+ this.redoStack = [];
+ }
+ get canUndo() { return this.undoStack.length > 0; }
+ get canRedo() { return this.redoStack.length > 0; }
+ get undoLabel() { return this.undoStack.at(-1)?.label || ''; }
+ get redoLabel() { return this.redoStack.at(-1)?.label || ''; }
+ // Both take the current state and return the one to restore, or null.
+ undo(current) {
+ const e = this.undoStack.pop();
+ if (!e) return null;
+ this.redoStack.push({ snapshot: JSON.stringify(current), label: e.label });
+ return { state: JSON.parse(e.snapshot), label: e.label };
+ }
+ redo(current) {
+ const e = this.redoStack.pop();
+ if (!e) return null;
+ this.undoStack.push({ snapshot: JSON.stringify(current), label: e.label });
+ return { state: JSON.parse(e.snapshot), label: e.label };
+ }
}
- const api = { newProfile, exportProfile, importProfile, normalizeStore, cleanKeys };
+ const api = {
+ DEFAULT_SETTINGS, HOST_TYPES, newProfile, cleanEntry, cleanKeys, isMapped, exportProfile, exportLibrary,
+ importProfile, importProfiles, normalizeStore, profileForApp, History,
+ };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.Profiles = api;
})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/app/renderer/protocol.js b/app/renderer/protocol.js
index 4ba45a7..3cf6070 100644
--- a/app/renderer/protocol.js
+++ b/app/renderer/protocol.js
@@ -1,5 +1,5 @@
// Keyword host protocol: newline-terminated ASCII lines, same over USB CDC and BLE.
-// See ../README.md for the full description.
+// See ../PROTOCOL.md for the full description.
(function (root) {
const SIDES = ['L', 'R', 'T'];
@@ -10,7 +10,10 @@
tx: '6e400003-b5a3-f393-e0a9-e50e24dcca9e', // keyword notifies here
};
- // Splits a byte/char stream into lines. Handles \r\n and partial chunks.
+ const MAX_MACRO_STEPS = 16;
+ const DEFAULT_HOLD_MS = 200;
+
+ // Splits a byte/char stream into lines ending in \n, \r\n or a bare \r. Handles partial chunks.
class LineBuffer {
constructor(onLine) {
this.buf = '';
@@ -19,9 +22,9 @@
push(text) {
this.buf += text;
let i;
- while ((i = this.buf.indexOf('\n')) >= 0) {
- const line = this.buf.slice(0, i).replace(/\r$/, '').trim();
- this.buf = this.buf.slice(i + 1);
+ while ((i = this.buf.search(/[\r\n]/)) >= 0) {
+ const line = this.buf.slice(0, i).trim();
+ this.buf = this.buf.slice(i + 1); // a \r\n leaves an empty line, which is skipped
if (line) this.onLine(line);
}
if (this.buf.length > 4096) this.buf = ''; // garbage with no newline
@@ -41,33 +44,53 @@
const isUid = (u) => typeof u === 'string' && /^([0-9a-fA-F]{24}|[0-9a-fA-F]{8})$/.test(u);
const hex2 = (n) => (n & 0xff).toString(16).toUpperCase().padStart(2, '0');
const hex4 = (n) => (n & 0xffff).toString(16).toUpperCase().padStart(4, '0');
-
- // One profile entry -> the MAP/MAPC command for it, or null if it maps nothing.
- function mapCommand(uid, m) {
- if (m.consumer) return cmd.mapConsumer(uid, m.consumer);
- if (m.mods || m.key) return cmd.map(uid, m.mods || 0, m.key || 0);
- return null;
- }
+ const int = (s, radix = 10) => { const n = parseInt(s, radix); return Number.isFinite(n) ? n : 0; };
// Host -> Keyword commands.
const cmd = {
hello: () => 'HELLO',
sides: () => 'SIDES?',
keys: () => 'KEYS?',
+ battery: () => 'BATT?',
map: (uid, mods, key) => `MAP uid=${uid} mods=${hex2(mods)} key=${hex2(key)}`,
mapConsumer: (uid, usage) => `MAPC uid=${uid} usage=${hex4(usage)}`,
+ macro: (uid, steps) => `MACRO uid=${uid} seq=${steps.slice(0, MAX_MACRO_STEPS).map(([m, k]) => hex2(m) + hex2(k)).join(',')}`,
+ hold: (uid, mods, key, ms) => `HOLD uid=${uid} mods=${hex2(mods)} key=${hex2(key)} ms=${Math.round(ms || DEFAULT_HOLD_MS)}`,
mapQuery: (uid) => `MAP? uid=${uid}`,
unmap: (uid) => `UNMAP uid=${uid}`,
+ flash: (uid) => `FLASH uid=${uid}`,
clear: () => 'CLEAR',
save: () => 'SAVE',
};
+ const hasHold = (m) => !!(m.hold && (m.hold.mods || m.hold.key));
+
+ // One profile entry -> the commands that program it into the Keyword.
+ // Host actions (run by the app) and empty entries need nothing.
+ // caps is the set from HELLO; commands it doesn't list are left out.
+ function entryCommands(uid, m, caps) {
+ const out = [];
+ if (m.host) return out;
+ if (m.macro?.length) {
+ if (caps.has('macro')) out.push(cmd.macro(uid, m.macro));
+ } else if (m.consumer) out.push(cmd.mapConsumer(uid, m.consumer));
+ else if (m.mods || m.key) out.push(cmd.map(uid, m.mods || 0, m.key || 0));
+ if (hasHold(m) && caps.has('hold')) out.push(cmd.hold(uid, m.hold.mods || 0, m.hold.key || 0, m.hold.ms));
+ return out;
+ }
+
+ // Back-compat helper: the main MAP/MAPC command for an entry, or null.
+ function mapCommand(uid, m) {
+ if (m.consumer) return cmd.mapConsumer(uid, m.consumer);
+ if (m.mods || m.key) return cmd.map(uid, m.mods || 0, m.key || 0);
+ return null;
+ }
+
// Commands that make the Keyword match a profile exactly.
- function profileCommands(keys) {
+ function profileCommands(keys, caps = new Set()) {
const out = [cmd.clear()];
for (const [uid, m] of Object.entries(keys)) {
- const c = isUid(uid) && mapCommand(uid.toUpperCase(), m);
- if (c) out.push(c);
+ if (isUid(uid)) out.push(...entryCommands(uid.toUpperCase(), m, caps));
}
out.push(cmd.save());
return out;
@@ -76,11 +99,16 @@
// Returns {type, ...} or {type: 'unknown', line}.
function parseLine(line) {
const parts = line.trim().split(/\s+/);
- const cmd = parts[0];
+ const name = parts[0];
const f = parseFields(parts.slice(1));
- switch (cmd) {
+ const uid = isUid(f.uid) ? f.uid.toUpperCase() : null;
+ switch (name) {
case 'KEYWORD':
- return { type: 'hello', fw: f.v || '?', proto: Number(f.proto || 0) };
+ return {
+ type: 'hello', fw: f.v || '?', proto: int(f.proto),
+ caps: new Set((f.caps || '').split(',').filter(Boolean)),
+ kb: f.kb != null ? int(f.kb) : null,
+ };
case 'SIDES': {
const sides = {};
for (const s of SIDES) if (s in f) sides[s] = f[s] === '1';
@@ -88,23 +116,39 @@
return { type: 'sides', sides };
}
case 'KEY+':
- if (!isUid(f.uid)) break;
- return { type: 'keyAdd', uid: f.uid.toUpperCase(), at: SIDES.includes(f.at) ? f.at : null };
+ if (!uid) break;
+ return {
+ type: 'keyAdd', uid, at: SIDES.includes(f.at) ? f.at : null, v: f.v != null ? int(f.v) : null,
+ // Keybits relayed through another Keybit: at=X, via=<uid of the next Keybit in>, depth=<hops>.
+ ...(f.via ? { via: isUid(f.via) ? f.via.toUpperCase() : null, depth: int(f.depth) || null } : {}),
+ };
case 'KEY-':
- if (!isUid(f.uid)) break;
- return { type: 'keyRemove', uid: f.uid.toUpperCase() };
+ if (!uid) break;
+ return { type: 'keyRemove', uid };
case 'KEYS':
if (parts[1] === 'END') return { type: 'keysEnd' };
break;
case 'PRESS':
- if (!isUid(f.uid)) break;
- return { type: 'press', uid: f.uid.toUpperCase(), down: f.down === '1' };
+ if (!uid) break;
+ return { type: 'press', uid, down: f.down === '1' };
case 'MAP':
- if (!isUid(f.uid)) break;
- return { type: 'map', uid: f.uid.toUpperCase(), mods: parseInt(f.mods || '0', 16) || 0, key: parseInt(f.key || '0', 16) || 0 };
+ if (!uid) break;
+ return { type: 'map', uid, mods: int(f.mods, 16), key: int(f.key, 16) };
case 'MAPC':
- if (!isUid(f.uid)) break;
- return { type: 'mapConsumer', uid: f.uid.toUpperCase(), usage: parseInt(f.usage || '0', 16) || 0 };
+ if (!uid) break;
+ return { type: 'mapConsumer', uid, usage: int(f.usage, 16) };
+ case 'MACRO':
+ if (!uid) break;
+ return { type: 'macro', uid, steps: (f.seq || '').split(',').filter((s) => /^[0-9a-fA-F]{4}$/.test(s)).map((s) => [int(s.slice(0, 2), 16), int(s.slice(2), 16)]) };
+ case 'HOLD':
+ if (!uid) break;
+ return { type: 'hold', uid, mods: int(f.mods, 16), key: int(f.key, 16), ms: int(f.ms) || DEFAULT_HOLD_MS };
+ case 'BATT':
+ if (f.pct == null) break;
+ return { type: 'battery', pct: Math.max(0, Math.min(100, int(f.pct))), charging: f.chg === '1', usb: f.usb === '1' };
+ case 'FLASH':
+ if (!uid) break;
+ return { type: 'flashProgress', uid, pct: Math.max(0, Math.min(100, int(f.pct))) };
case 'OK':
return { type: 'ok', what: parts[1] || '', ...parseFields(parts.slice(2)) };
case 'ERR':
@@ -113,7 +157,10 @@
return { type: 'unknown', line };
}
- const api = { SIDES, NUS, LineBuffer, parseLine, cmd, mapCommand, profileCommands, isUid };
+ const api = {
+ SIDES, NUS, MAX_MACRO_STEPS, DEFAULT_HOLD_MS, LineBuffer, parseLine, cmd,
+ mapCommand, entryCommands, profileCommands, isUid, hasHold,
+ };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.KeywordProtocol = api;
})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/app/renderer/templates.js b/app/renderer/templates.js
new file mode 100644
index 0000000..0c38249
--- /dev/null
+++ b/app/renderer/templates.js
@@ -0,0 +1,79 @@
+// Ready-made profiles. Each template is a list of actions that get handed out to
+// Keybits in order (left, top edge, right, then the rest), so a 3-key setup takes
+// the first three.
+(function (root) {
+ // Modifier bits: 1 Ctrl, 2 Shift, 4 Alt, 8 GUI (Cmd/Win).
+ const C = 1, S = 2, A = 4, G = 8;
+ const k = (key, mods = 0, name) => ({ mods, key, ...(name ? { name } : {}) });
+ const media = (consumer, name) => ({ consumer, mods: 0, key: 0, name });
+ // HID usages used below.
+ const U = {
+ A: 0x04, C: 0x06, D: 0x07, E: 0x08, L: 0x0f, P: 0x13, Q: 0x14, R: 0x15, S: 0x16, T: 0x17, V: 0x19, W: 0x1a, X: 0x1b, Y: 0x1c, Z: 0x1d,
+ N3: 0x20, N4: 0x21, N5: 0x22, Space: 0x2c, Slash: 0x38, Backquote: 0x35, BracketL: 0x2f, BracketR: 0x30,
+ F5: 0x3e, F11: 0x44, PrintScreen: 0x46, Left: 0x50, Right: 0x4f, Up: 0x52, F13: 0x68,
+ };
+
+ // Each build(mac) returns the action list for that platform.
+ const TEMPLATES = [
+ {
+ id: 'media', name: 'Media controls', description: 'Play/pause, skip and volume.',
+ build: () => [media(0xcd, 'Play/Pause'), media(0xb6, 'Previous'), media(0xb5, 'Next'),
+ media(0xe2, 'Mute'), media(0xea, 'Volume down'), media(0xe9, 'Volume up')],
+ },
+ {
+ id: 'editing', name: 'Editing', description: 'Copy, paste, undo and friends.',
+ build: (mac) => { const M = mac ? G : C; return [k(U.C, M, 'Copy'), k(U.V, M, 'Paste'), k(U.Z, M, 'Undo'),
+ mac ? k(U.Z, G | S, 'Redo') : k(U.Y, C, 'Redo'), k(U.X, M, 'Cut'), k(U.A, M, 'Select all')]; },
+ },
+ {
+ id: 'meetings', name: 'Meetings', description: 'Mute and camera for Zoom and Google Meet.', apps: ['zoom.us', 'Zoom'],
+ build: (mac) => mac
+ ? [k(U.A, G | S, 'Zoom mute'), k(U.V, G | S, 'Zoom video'), k(U.D, G, 'Meet mute'), k(U.E, G, 'Meet camera')]
+ : [k(U.A, A, 'Zoom mute'), k(U.V, A, 'Zoom video'), k(U.D, C, 'Meet mute'), k(U.E, C, 'Meet camera')],
+ },
+ {
+ id: 'stream', name: 'Streaming (F13+)', description: 'F13 to F18, which no app uses by default. Bind them as hotkeys in OBS.',
+ build: () => [0, 1, 2, 3, 4, 5].map((i) => k(U.F13 + i, 0, `Scene ${i + 1}`)),
+ },
+ {
+ id: 'screens', name: 'Screenshots', description: 'Whole screen, area and the capture toolbar.',
+ build: (mac) => mac
+ ? [k(U.N3, G | S, 'Full screen'), k(U.N4, G | S, 'Area'), k(U.N5, G | S, 'Capture menu')]
+ : [k(U.PrintScreen, 0, 'Full screen'), k(U.S, G | S, 'Snip area')],
+ },
+ {
+ id: 'browser', name: 'Browser', description: 'Tabs, history and reload.',
+ build: (mac) => { const M = mac ? G : C; return [k(U.T, M, 'New tab'), k(U.W, M, 'Close tab'), k(U.T, M | S, 'Reopen tab'),
+ mac ? k(U.BracketL, G, 'Back') : k(U.Left, A, 'Back'), mac ? k(U.BracketR, G, 'Forward') : k(U.Right, A, 'Forward'), k(U.R, M, 'Reload')]; },
+ },
+ {
+ id: 'code', name: 'VS Code', description: 'Command palette, quick open, terminal and comments.', apps: ['Code', 'Visual Studio Code'],
+ build: (mac) => { const M = mac ? G : C; return [k(U.P, M | S, 'Commands'), k(U.P, M, 'Quick open'), k(U.Backquote, C, 'Terminal'),
+ k(U.Slash, M, 'Comment'), k(U.F5, 0, 'Run/debug')]; },
+ },
+ {
+ id: 'system', name: 'System', description: 'Search, lock screen and overview.',
+ build: (mac) => mac
+ ? [k(U.Space, G, 'Spotlight'), k(U.Q, C | G, 'Lock screen'), k(U.Up, C, 'Mission Control')]
+ : [k(0, G, 'Start menu'), k(U.L, G, 'Lock screen'), k(U.D, G, 'Show desktop')],
+ },
+ ];
+
+ // Order Keybits are handed actions in.
+ const SIDE_ORDER = { L: 0, T: 1, R: 2 };
+ function orderUids(uids, sideOf) {
+ return [...uids].sort((a, b) => (SIDE_ORDER[sideOf(a)] ?? 9) - (SIDE_ORDER[sideOf(b)] ?? 9) || a.localeCompare(b));
+ }
+
+ // Template -> { keys, apps, used, extra } for the given Keybits.
+ function applyTemplate(t, uids, mac) {
+ const actions = t.build(mac);
+ const keys = {};
+ uids.slice(0, actions.length).forEach((uid, i) => { keys[uid] = actions[i]; });
+ return { keys, apps: t.apps || [], used: Math.min(uids.length, actions.length), total: actions.length };
+ }
+
+ const api = { TEMPLATES, applyTemplate, orderUids };
+ if (typeof module !== 'undefined' && module.exports) module.exports = api;
+ else root.Templates = api;
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/app/test/hid.test.js b/app/test/hid.test.js
index 6212faf..5532ee3 100644
--- a/app/test/hid.test.js
+++ b/app/test/hid.test.js
@@ -30,3 +30,15 @@ test('media keys', () => {
assert.deepStrictEqual(Hid.fromEvent({ code: 'MediaPlayPause' }), { consumer: 0xcd });
assert.strictEqual(Hid.consumerLabel(0xe9), 'Volume Up');
});
+
+test('text to macro steps', () => {
+ assert.deepStrictEqual(Hid.textToSteps('aB1!').steps, [[0, 4], [2, 5], [0, 0x1e], [2, 0x1e]]);
+ assert.deepStrictEqual(Hid.textToSteps('é').skipped, ['é']);
+ assert.strictEqual(Hid.macroLabel([...Hid.textToSteps('Hi').steps, [8, 0x06]], true), '"Hi", Cmd+C');
+});
+
+test('search finds keys and media keys', () => {
+ assert.strictEqual(Hid.search('f13')[0].label, 'F13');
+ assert.deepStrictEqual(Hid.search('play')[0], { kind: 'c', usage: 0xcd, label: 'Play/Pause' });
+ assert.strictEqual(Hid.search('zzzz').length, 0);
+});
diff --git a/app/test/profiles.test.js b/app/test/profiles.test.js
index 5121cf3..9f3cb29 100644
--- a/app/test/profiles.test.js
+++ b/app/test/profiles.test.js
@@ -34,3 +34,53 @@ test('consumer entries survive a round trip', () => {
const p = P.importProfile(P.exportProfile(P.newProfile('M', { '5F1821C1': { consumer: 0xcd, mods: 3 } })));
assert.deepStrictEqual(p.keys, { '5F1821C1': { mods: 0, key: 0, consumer: 0xcd } });
});
+
+test('entries keep macro, hold and host actions', () => {
+ const keys = P.cleanKeys({
+ '5F1821C1': { macro: [[1, 6], [1, 0x19, 9], ['x', 4]], hold: { mods: 2, ms: 5 } },
+ '0A33B7E2': { host: { type: 'url', value: 'https://a.b' }, name: ' Docs ' },
+ '00000001': { host: { type: 'evil', value: 'x' }, key: 4 },
+ });
+ assert.deepStrictEqual(keys['5F1821C1'], { macro: [[1, 6], [0, 4]], hold: { mods: 2, key: 0, ms: 50 } });
+ assert.deepStrictEqual(keys['0A33B7E2'], { host: { type: 'url', value: 'https://a.b' }, name: 'Docs' });
+ assert.deepStrictEqual(keys['00000001'], { mods: 0, key: 4 });
+ assert.strictEqual(P.isMapped({ mods: 0, key: 0 }), false);
+ assert.strictEqual(P.isMapped(keys['0A33B7E2']), true);
+});
+
+test('library export imports as several profiles', () => {
+ const a = P.newProfile('A', { '5F1821C1': { key: 4 } }, ['Figma']);
+ const b = P.newProfile('B');
+ const out = P.importProfiles(P.exportLibrary([a, b]));
+ assert.deepStrictEqual(out.map((p) => [p.name, p.apps]), [['A', ['Figma']], ['B', []]]);
+ assert.throws(() => P.importProfiles('{"format":"keyword-profile-library","version":1}'), /no profiles/);
+});
+
+test('settings are kept and repaired', () => {
+ const s = P.normalizeStore({ settings: { theme: 'neon', perApp: true, autoReconnect: 'yes', lastConnection: { kind: 'ble', id: 'x' } }, stats: { A: 3, B: -1, C: 'x' } });
+ assert.strictEqual(s.settings.theme, 'system');
+ assert.strictEqual(s.settings.perApp, true);
+ assert.strictEqual(s.settings.autoReconnect, true);
+ assert.deepStrictEqual(s.settings.lastConnection, { kind: 'ble', id: 'x' });
+ assert.deepStrictEqual(s.stats, { A: 3 });
+});
+
+test('per-app lookup is case-insensitive', () => {
+ const ps = [P.newProfile('Zoom', {}, ['zoom.us']), P.newProfile('Code', {}, ['Code'])];
+ assert.strictEqual(P.profileForApp(ps, 'ZOOM.US').name, 'Zoom');
+ assert.strictEqual(P.profileForApp(ps, 'Safari'), null);
+});
+
+test('history undoes and redoes', () => {
+ const h = new P.History(2);
+ let state = { n: 1 };
+ h.record(state, 'one'); state = { n: 2 };
+ h.record(state, 'two'); state = { n: 3 };
+ h.record(state, 'three'); state = { n: 4 }; // oldest entry drops (limit 2)
+ let r = h.undo(state); assert.deepStrictEqual([r.state, r.label], [{ n: 3 }, 'three']); state = r.state;
+ r = h.undo(state); assert.deepStrictEqual(r.state, { n: 2 }); state = r.state;
+ assert.strictEqual(h.undo(state), null);
+ r = h.redo(state); assert.deepStrictEqual(r.state, { n: 3 }); state = r.state;
+ h.record(state, 'new');
+ assert.strictEqual(h.canRedo, false);
+});
diff --git a/app/test/protocol.test.js b/app/test/protocol.test.js
index 46d3804..2b66127 100644
--- a/app/test/protocol.test.js
+++ b/app/test/protocol.test.js
@@ -15,12 +15,15 @@ test('SIDES with only some fields', () => {
});
test('parses HELLO reply', () => {
- assert.deepStrictEqual(parseLine('KEYWORD v=0.1 proto=1'), { type: 'hello', fw: '0.1', proto: 1 });
+ assert.deepStrictEqual(parseLine('KEYWORD v=0.1 proto=1'), { type: 'hello', fw: '0.1', proto: 1, caps: new Set(), kb: null });
+ const h = parseLine('KEYWORD v=0.2 proto=1 caps=batt,hold kb=3');
+ assert.deepStrictEqual([...h.caps], ['batt', 'hold']);
+ assert.strictEqual(h.kb, 3);
});
test('accepts 96-bit UIDs', () => {
const uid = '3B0A4F1C88D2E61F5F1821C1';
- assert.deepStrictEqual(parseLine(`KEY+ uid=${uid.toLowerCase()} at=L`), { type: 'keyAdd', uid, at: 'L' });
+ assert.deepStrictEqual(parseLine(`KEY+ uid=${uid.toLowerCase()} at=L`), { type: 'keyAdd', uid, at: 'L', v: null });
assert.strictEqual(cmd.map(uid, 1, 4), `MAP uid=${uid} mods=01 key=04`);
assert.strictEqual(parseLine('KEY+ uid=3B0A4F1C88D2 at=L').type, 'unknown');
});
@@ -39,8 +42,8 @@ test('line buffer splits chunks and CRLF', () => {
});
test('parses key events', () => {
- assert.deepStrictEqual(parseLine('KEY+ uid=5f1821c1 at=R'), { type: 'keyAdd', uid: '5F1821C1', at: 'R' });
- assert.deepStrictEqual(parseLine('KEY+ uid=5F1821C1 at=?'), { type: 'keyAdd', uid: '5F1821C1', at: null });
+ assert.deepStrictEqual(parseLine('KEY+ uid=5f1821c1 at=R'), { type: 'keyAdd', uid: '5F1821C1', at: 'R', v: null });
+ assert.deepStrictEqual(parseLine('KEY+ uid=5F1821C1 at=?'), { type: 'keyAdd', uid: '5F1821C1', at: null, v: null });
assert.deepStrictEqual(parseLine('KEY- uid=5F1821C1'), { type: 'keyRemove', uid: '5F1821C1' });
assert.deepStrictEqual(parseLine('PRESS uid=5F1821C1 down=1'), { type: 'press', uid: '5F1821C1', down: true });
assert.deepStrictEqual(parseLine('KEYS END'), { type: 'keysEnd' });
@@ -65,3 +68,32 @@ test('media key mappings', () => {
assert.deepStrictEqual(parseLine('MAPC uid=5F1821C1 usage=00E9'), { type: 'mapConsumer', uid: '5F1821C1', usage: 0xe9 });
assert.deepStrictEqual(profileCommands({ '5F1821C1': { consumer: 0x192 } }), ['CLEAR', 'MAPC uid=5F1821C1 usage=0192', 'SAVE']);
});
+
+test('optional features: battery, macro, hold, flash', () => {
+ const { entryCommands } = require('../renderer/protocol.js');
+ assert.deepStrictEqual(parseLine('BATT pct=81 chg=1 usb=1'), { type: 'battery', pct: 81, charging: true, usb: true });
+ assert.deepStrictEqual(parseLine('MACRO uid=5F1821C1 seq=0006,0119,zz'), { type: 'macro', uid: '5F1821C1', steps: [[0, 6], [1, 0x19]] });
+ assert.deepStrictEqual(parseLine('HOLD uid=5F1821C1 mods=02 key=00 ms=250'), { type: 'hold', uid: '5F1821C1', mods: 2, key: 0, ms: 250 });
+ assert.deepStrictEqual(parseLine('FLASH uid=5F1821C1 pct=40'), { type: 'flashProgress', uid: '5F1821C1', pct: 40 });
+ assert.deepStrictEqual(parseLine('KEY+ uid=5F1821C1 at=L v=2').v, 2);
+
+ const all = new Set(['macro', 'hold']);
+ const e = { macro: [[1, 6], [1, 0x19]], hold: { mods: 2, key: 0, ms: 300 } };
+ assert.deepStrictEqual(entryCommands('5F1821C1', e, all), ['MACRO uid=5F1821C1 seq=0106,0119', 'HOLD uid=5F1821C1 mods=02 key=00 ms=300']);
+ assert.deepStrictEqual(entryCommands('5F1821C1', e, new Set()), [], 'unsupported features are not sent');
+ assert.deepStrictEqual(entryCommands('5F1821C1', { host: { type: 'url', value: 'x' } }, all), []);
+ assert.strictEqual(cmd.macro('5F1821C1', Array(20).fill([0, 4])).split(',').length, 16);
+});
+
+test('line buffer accepts a bare CR', () => {
+ const lines = [];
+ const lb = new LineBuffer((l) => lines.push(l));
+ lb.push('HELLO\rSIDES?\r');
+ lb.push('\nKEYS?\n');
+ assert.deepStrictEqual(lines, ['HELLO', 'SIDES?', 'KEYS?']);
+});
+
+test('relayed Keybits', () => {
+ assert.deepStrictEqual(parseLine('KEY+ uid=D00DF00D at=X via=91C7002DE4B3A75C0A33B7E2 depth=2 v=3'),
+ { type: 'keyAdd', uid: 'D00DF00D', at: null, v: 3, via: '91C7002DE4B3A75C0A33B7E2', depth: 2 });
+});
diff --git a/app/test/templates.test.js b/app/test/templates.test.js
new file mode 100644
index 0000000..a309cf2
--- /dev/null
+++ b/app/test/templates.test.js
@@ -0,0 +1,25 @@
+const test = require('node:test');
+const assert = require('node:assert');
+const T = require('../renderer/templates.js');
+const P = require('../renderer/profiles.js');
+
+test('every template builds valid entries on both platforms', () => {
+ for (const t of T.TEMPLATES) {
+ for (const mac of [true, false]) {
+ const actions = t.build(mac);
+ assert.ok(actions.length > 0, t.id);
+ for (const a of actions) assert.ok(P.isMapped(P.cleanEntry(a)), `${t.id} ${JSON.stringify(a)}`);
+ }
+ }
+});
+
+test('templates fill keys left, top, right', () => {
+ const side = { A: 'R', B: 'L', C: 'T' };
+ const uids = T.orderUids(['A', 'B', 'C'], (u) => side[u]);
+ assert.deepStrictEqual(uids, ['B', 'C', 'A']);
+ const media = T.TEMPLATES.find((t) => t.id === 'media');
+ const r = T.applyTemplate(media, uids, true);
+ assert.strictEqual(r.used, 3);
+ assert.strictEqual(r.keys.B.consumer, 0xcd);
+ assert.strictEqual(r.total, 6);
+});