A truly modular keyboard
C
app: redesigned UI with macros, hold actions, settings and undo
Nathan88c416a2cfc5
diff --git a/app/renderer/app.js b/app/renderer/app.jsindex fd60fc6..4160bf3 100644--- a/app/renderer/app.js+++ b/app/renderer/app.js@@ -1,19 +1,25 @@-/* global KeywordProtocol, Hid, Profiles */-const { SIDES, NUS, LineBuffer, parseLine, cmd, mapCommand, profileCommands } = KeywordProtocol;+/* global KeywordProtocol, Hid, Profiles, Templates */+const { SIDES, NUS, LineBuffer, parseLine, cmd, entryCommands, profileCommands, hasHold, MAX_MACRO_STEPS, DEFAULT_HOLD_MS } = KeywordProtocol;-const POLL_MS = 2000; // ask for SIDES? this often in case a push was missed+const POLL_MS = 2000; // ask for SIDES? this often in case a push was missedconst KEYS_POLL_MS = 10000; // full KEYS? resync-const STALE_MS = 5000; // no line from the Keyword for this long means stale+const BATT_POLL_MS = 30000;+const STALE_MS = 5000; // no line from the Keyword for this long means staleconst SIDE_NAMES = { L: 'left', R: 'right', T: 'top edge' };const MAC = /Mac/i.test(navigator.platform);+const MOD_KEY = MAC ? 'Cmd' : 'Ctrl';+// Clicking our own window shouldn't count as "switched app" for per-app profiles.+const SELF_APPS = new Set(['keyword monitor', 'electron', 'keyword-monitor']);const $ = (sel) => document.querySelector(sel);+const $$ = (sel) => [...document.querySelectorAll(sel)];const el = (tag, props = {}, ...children) => {const e = Object.assign(document.createElement(tag), props);- e.append(...children.filter((c) => c != null));+ e.append(...children.filter((c) => c != null && c !== false));return e;};const logEl = $('#log');+const bridge = window.desktop || null;function log(dir, text) {const t = new Date().toLocaleTimeString();@@ -26,9 +32,13 @@ function log(dir, text) {class SerialTransport {label = 'USB serial';+ kind = 'serial';+ constructor(port) { this.port = port || null; } // an already-granted port skips the pickerasync open(onText, onClose) {- this.port = await navigator.serial.requestPort();+ if (!this.port) this.port = await navigator.serial.requestPort();await this.port.open({ baudRate: 115200 }); // CDC ignores the baud rate+ // The Keyword only pushes events once DTR is set.+ try { await this.port.setSignals({ dataTerminalReady: true }); } catch {}this.writer = this.port.writable.getWriter();this.closed = false;(async () => {@@ -52,6 +62,10 @@ class SerialTransport {if (!this.closed) onClose();})();}+ identity() {+ const i = this.port.getInfo?.() || {};+ return { kind: 'serial', usbVendorId: i.usbVendorId ?? null, usbProductId: i.usbProductId ?? null };+ }async write(text) {await this.writer.write(new TextEncoder().encode(text));}@@ -65,13 +79,19 @@ class SerialTransport {class BleTransport {label = 'Bluetooth';+ kind = 'ble';+ constructor(device) { this.device = device || null; }async open(onText, onClose) {- this.device = await navigator.bluetooth.requestDevice({- // NUS's 128-bit UUID isn't advertised, so match on the name.- filters: [{ namePrefix: 'Keyword' }],- optionalServices: [NUS.service],- });- this.device.addEventListener('gattserverdisconnected', () => { if (!this.closed) onClose(); });+ if (!this.device) {+ this.device = await navigator.bluetooth.requestDevice({+ // NUS's 128-bit UUID isn't advertised, so match on the name.+ filters: [{ namePrefix: 'Keyword' }],+ optionalServices: [NUS.service],+ });+ }+ this.onClose = onClose;+ this.onDisconnect = () => { if (!this.closed) this.onClose(); };+ this.device.addEventListener('gattserverdisconnected', this.onDisconnect);const server = await this.device.gatt.connect();const svc = await server.getPrimaryService(NUS.service);this.rx = await svc.getCharacteristic(NUS.rx);@@ -82,6 +102,7 @@ class BleTransport {await tx.startNotifications();this.closed = false;}+ identity() { return { kind: 'ble', id: this.device.id, name: this.device.name || '' }; }async write(text) {const bytes = new TextEncoder().encode(text);for (let i = 0; i < bytes.length; i += 20) { // fits the default 23-byte ATT MTU@@ -92,97 +113,224 @@ class BleTransport {}async close() {this.closed = true;+ this.device?.removeEventListener('gattserverdisconnected', this.onDisconnect);if (this.device?.gatt.connected) this.device.gatt.disconnect();}}-// Pretends to be a Keyword so the app can be tried without hardware.+// Pretends to be a Keyword (with every optional feature) so the app can be tried without hardware.class DemoTransport {label = 'Demo';+ kind = 'demo';uids = { L: '3B0A4F1C88D2E61F5F1821C1', R: '91C7002DE4B3A75C0A33B7E2', T: '0F5E19A2C6B84D37C4D90015' };+ versions = { L: 3, R: 2, T: 3 };present = { L: true, R: false, T: false };maps = {};- async open(onText) { this.onText = onText; }- emit(line) { setTimeout(() => this.onText(line + '\n'), 20); }+ battery = 82;+ kb = 3;+ async open(onText) {+ this.onText = onText;+ this.battTimer = setInterval(() => {+ if (this.battery > 5) { this.battery -= 1; this.emit(this.battLine()); }+ }, 20000);+ }+ identity() { return { kind: 'demo' }; }+ emit(line) { setTimeout(() => this.onText?.(line + '\n'), 20); }+ battLine() { return `BATT pct=${this.battery} chg=0 usb=0`; }sidesLine() { return 'SIDES ' + SIDES.map((s) => `${s}=${this.present[s] ? 1 : 0}`).join(' '); }+ keyLine(s) { return `KEY+ uid=${this.uids[s]} at=${s} v=${this.versions[s]}`; }+ // A Keybit chained behind the right one, reported by its low 32 bits like a real relay.+ chained = 'D00DF00D';+ chainedLine() { return `KEY+ uid=${this.chained} at=X via=${this.uids.R} depth=1 v=3`; }toggle(side) {this.present[side] = !this.present[side];- this.emit(this.present[side] ? `KEY+ uid=${this.uids[side]} at=${side}` : `KEY- uid=${this.uids[side]}`);+ this.emit(this.present[side] ? this.keyLine(side) : `KEY- uid=${this.uids[side]}`);+ if (side === 'R') this.emit(this.present.R ? this.chainedLine() : `KEY- uid=${this.chained}`);this.emit(this.sidesLine());}+ sideOf(uid) { return SIDES.find((s) => this.uids[s] === uid && this.present[s]) || (uid === this.chained && this.present.R ? 'X' : undefined); }tap(uid) {- if (!Object.entries(this.uids).some(([s, u]) => u === uid && this.present[s])) return;+ if (!this.sideOf(uid)) return;this.emit(`PRESS uid=${uid} down=1`);setTimeout(() => this.emit(`PRESS uid=${uid} down=0`), 180);}+ flash(uid) {+ const s = this.sideOf(uid);+ if (!s) return this.emit(`ERR flash ${uid} not present`);+ if (s === 'X') return this.emit('ERR flash only Keybits touching the Keyword can be reflashed');+ let pct = 0;+ const t = setInterval(() => {+ pct += 20;+ this.emit(`FLASH uid=${uid} pct=${pct}`);+ if (pct >= 100) {+ clearInterval(t);+ this.versions[s] = this.kb;+ this.emit(`OK FLASH uid=${uid}`);+ this.emit(this.keyLine(s));+ }+ }, 300);+ }async write(text) {for (const line of text.split('\n').map((s) => s.trim()).filter(Boolean)) {const [c] = line.split(' ');const f = Object.fromEntries(line.split(' ').slice(1).map((p) => p.split('=')));- if (c === 'HELLO') this.emit('KEYWORD v=demo proto=1');+ if (c === 'HELLO') this.emit(`KEYWORD v=demo proto=1 caps=batt,hold,macro,flash kb=${this.kb}`);else if (c === 'SIDES?') this.emit(this.sidesLine());+ else if (c === 'BATT?') this.emit(this.battLine());else if (c === 'KEYS?') {- for (const s of SIDES) if (this.present[s]) this.emit(`KEY+ uid=${this.uids[s]} at=${s}`);+ for (const s of SIDES) if (this.present[s]) this.emit(this.keyLine(s));+ if (this.present.R) this.emit(this.chainedLine());this.emit('KEYS END');- } else if (c === 'MAP') { this.maps[f.uid] = f; this.emit(`OK MAP uid=${f.uid}`); }- else if (c === 'MAPC') { this.maps[f.uid] = f; this.emit(`OK MAPC uid=${f.uid}`); }+ } else if (['MAP', 'MAPC', 'MACRO', 'HOLD'].includes(c)) { this.maps[f.uid] = f; this.emit(`OK ${c} uid=${f.uid}`); }else if (c === 'UNMAP') { delete this.maps[f.uid]; this.emit(`OK UNMAP uid=${f.uid}`); }else if (c === 'CLEAR') { this.maps = {}; this.emit('OK CLEAR'); }else if (c === 'SAVE') this.emit('OK SAVE');+ else if (c === 'FLASH') this.flash(f.uid);else this.emit(`ERR unknown command ${c}`);}}- async close() {}+ async close() { clearInterval(this.battTimer); this.onText = null; }}-// ---- Profiles (persisted by main.js, or localStorage when run in a browser) ----+// ---- Saved state (main.js writes it to disk; localStorage when run in a browser) -----const storage = window.desktop- ? { load: () => window.desktop.loadStore(), save: (s) => window.desktop.saveStore(s) }+const storage = bridge+ ? { load: () => bridge.loadStore(), save: (s) => bridge.saveStore(s) }: {load: async () => { try { return JSON.parse(localStorage.getItem('keyword-profiles')); } catch { return null; } },save: async (s) => { try { localStorage.setItem('keyword-profiles', JSON.stringify(s)); } catch {} },};let store = Profiles.normalizeStore(null);-const activeProfile = () => store.profiles.find((p) => p.id === store.active);+const history = new Profiles.History();+const activeProfile = () => store.profiles.find((p) => p.id === store.active) || store.profiles[0];+const settings = () => store.settings;++let saveTimer = null;function persist() {- storage.save(store).catch((e) => log('!!', `could not save profiles: ${e.message}`));+ clearTimeout(saveTimer);+ saveTimer = setTimeout(() => storage.save(store).catch((e) => log('!!', `could not save: ${e.message}`)), 150);+}++// Every user edit goes through here so it can be undone.+// sync: 'full' pushes the whole profile to the Keyword afterwards; a function runs custom sync.+function mutate(label, fn, sync = 'full') {+ history.record({ active: store.active, profiles: store.profiles }, label);+ fn();+ persist();+ render();+ if (sync === 'full') applyProfile(true);+ else if (typeof sync === 'function') sync();+}++function restore(entry, verb) {+ if (!entry) return;+ store.profiles = Profiles.normalizeStore({ ...entry.state, settings: store.settings }).profiles;+ store.active = entry.state.active;+ manualActive = store.active;+ persist();+ render();+ applyProfile(true);+ toast(`${verb} ${entry.label}`);}+const undo = () => restore(history.undo({ active: store.active, profiles: store.profiles }), 'Undid');+const redo = () => restore(history.redo({ active: store.active, profiles: store.profiles }), 'Redid');// ---- Connection state ----let transport = null;let timers = [];let lastRx = 0;-const keys = new Map(); // uid -> { at, pressed } for Keybits the Keyword reports-let sides = {}; // from SIDES lines-let syncSeen = null; // uids seen during a KEYS? reply+let device = { fw: null, caps: new Set(), kb: null, battery: null };+const keys = new Map(); // uid -> { at, pressed, v, flashing } for Keybits the Keyword reports+let sides = {}; // from SIDES lines+let syncSeen = null; // uids seen during a KEYS? reply+let reconnect = null; // { timer, tries } while trying to get a dropped link back+let flashUid = null; // card to highlight on the next render+let frontApp = null;+let manualActive = null; // profile the user picked by hand, for returning after per-app switches+let autoSwitched = false;+const seenApps = new Set();++const caps = () => device.caps;+const can = (c) => caps().has(c);function setStatus(text, cls) {$('#status-text').textContent = text;$('#status').className = 'status ' + (cls || '');+ pushState();}function activity(text, cls) {const list = $('#activity');list.prepend(el('li', { className: cls || '' }, el('time', { textContent: new Date().toLocaleTimeString() }), el('span', { textContent: text })));- while (list.children.length > 100) list.lastChild.remove();+ while (list.children.length > 200) list.lastChild.remove();+}++function toast(text, opts = {}) {+ const t = el('div', { className: 'toast' + (opts.error ? ' error' : '') }, el('span', { textContent: text }));+ if (opts.undo) t.append(el('button', { className: 'link', textContent: 'Undo', onclick: () => { undo(); t.remove(); } }));+ $('#toasts').append(t);+ setTimeout(() => t.classList.add('out'), opts.ms || 4000);+ setTimeout(() => t.remove(), (opts.ms || 4000) + 400);+}++function notify(title, body) {+ if (!settings().notifications || document.hasFocus()) return;+ try { new Notification(title, { body, silent: true }); } catch {}}const shortUid = (uid) => uid.slice(-4);-const keyName = (uid) => activeProfile().keys[uid]?.name || `Keybit ${shortUid(uid)}`;-const comboFor = (uid) => {- const m = activeProfile().keys[uid];+const entryOf = (uid) => activeProfile().keys[uid];+const keyName = (uid) => entryOf(uid)?.name || `Keybit ${shortUid(uid)}`;++function hostLabel(h) {+ switch (h.type) {+ case 'url': return `Open ${h.value.replace(/^https?:\/\//, '')}`;+ case 'app': return `Open ${h.value}`;+ case 'cmd': return `Run ${h.value}`;+ case 'next-profile': return 'Next profile';+ case 'profile': return `Profile: ${store.profiles.find((p) => p.id === h.value)?.name || '?'}`;+ }+ return '?';+}++// Short label for what an entry does, or '' if nothing.+function actionLabel(m) {if (!m) return '';- return m.consumer ? Hid.consumerLabel(m.consumer) : Hid.comboLabel(m.mods, m.key, MAC);-};+ if (m.host) return hostLabel(m.host);+ if (m.macro?.length) return Hid.macroLabel(m.macro, MAC);+ if (m.consumer) return Hid.consumerLabel(m.consumer);+ return Hid.comboLabel(m.mods || 0, m.key || 0, MAC);+}+const comboFor = (uid) => actionLabel(entryOf(uid));+const holdLabel = (h) => (h && (h.mods || h.key) ? Hid.comboLabel(h.mods, h.key, MAC) : '');++// Relayed Keybits may only be reported by their low 32 bits. Map those to a full+// UID we already know (connected, or set up in any profile) so they keep their setup.+function resolveUid(uid) {+ if (!uid || uid.length !== 8) return uid;+ const known = [...keys.keys(), ...store.profiles.flatMap((p) => Object.keys(p.keys))];+ return known.find((u) => u.length === 24 && u.endsWith(uid)) || uid;+}-function addKey(uid, at, quiet) {+function addKey(uid, at, v, relay) {const known = keys.get(uid);- keys.set(uid, { at, pressed: known?.pressed || false });- if (!known && !quiet) {- activity(`${keyName(uid)} connected${at ? ` on the ${SIDE_NAMES[at]}` : ''}`, 'add');+ // Seen in full for the first time: carry over a setup saved under its short UID.+ if (!known && uid.length === 24) {+ for (const p of store.profiles) {+ const short = uid.slice(-8);+ if (p.keys[short] && !p.keys[uid]) { p.keys[uid] = p.keys[short]; delete p.keys[short]; persist(); }+ }+ }+ keys.set(uid, {+ at, pressed: known?.pressed || false, v: v ?? known?.v ?? null, flashing: known?.flashing ?? null,+ via: relay?.via ? resolveUid(relay.via) : known?.via ?? null, depth: relay?.depth ?? known?.depth ?? null,+ });+ if (!known) {+ const where = at ? ` on the ${SIDE_NAMES[at]}` : relay?.via ? ` behind ${keyName(resolveUid(relay.via))}` : '';+ activity(`${keyName(uid)} connected${where}`, 'add');+ notify('Keybit connected', `${keyName(uid)}${where}`);flashUid = uid;}}@@ -190,68 +338,174 @@ function removeKey(uid) {if (!keys.has(uid)) return;const { at } = keys.get(uid);keys.delete(uid);- activity(`${keyName(uid)} disconnected${at ? ` from the ${SIDE_NAMES[at]}` : ''}`, 'remove');+ const where = at ? ` from the ${SIDE_NAMES[at]}` : '';+ activity(`${keyName(uid)} disconnected${where}`, 'remove');+ notify('Keybit disconnected', `${keyName(uid)}${where}`);}-let flashUid = null;+const outdated = (k) => k?.v != null && device.kb != null && k.v < device.kb;++// ---- Rendering ----function render() {+ const p = activeProfile();+// Boardfor (const s of SIDES) {const uid = [...keys].find(([, k]) => k.at === s)?.[0];const present = !!uid || !!sides[s];const slot = $(`.slot[data-side="${s}"]`);slot.classList.toggle('present', present);+ slot.classList.toggle('pressed', !!(uid && keys.get(uid).pressed));slot.querySelector('.slot-label').textContent = !present ? '' : uid ? (comboFor(uid) || keyName(uid)) : 'Keybit';slot.title = uid ? `${keyName(uid)} · uid ${uid}` : '';+ slot.dataset.uid = uid || '';}+ $('#board-profile').textContent = p.name;// Key list: connected first (left, top, right), then mapped keys that are offline.const order = { L: 0, T: 1, R: 2 };const online = [...keys].sort((a, b) => (order[a[1].at] ?? 9) - (order[b[1].at] ?? 9)).map(([u]) => u);- const offline = Object.keys(activeProfile().keys).filter((u) => !keys.has(u)).sort();+ const offline = Object.keys(p.keys).filter((u) => !keys.has(u)).sort();+ const q = $('#key-filter').value.trim().toLowerCase();+ const matches = (uid) => !q || [keyName(uid), comboFor(uid), uid, holdLabel(entryOf(uid)?.hold)].join(' ').toLowerCase().includes(q);const list = $('#keys');list.replaceChildren();- for (const uid of [...online, ...offline]) {- const k = keys.get(uid);- const combo = comboFor(uid);- const where = k ? (k.at ? SIDE_NAMES[k.at][0].toUpperCase() + SIDE_NAMES[k.at].slice(1) : 'Connected') : 'Not connected';- const btns = el('div', { className: 'btns' });- btns.append(el('button', { className: 'ghost small', textContent: 'Assign…', onclick: () => openAssign(uid) }));- if (k && transport instanceof DemoTransport) {- btns.append(el('button', { className: 'ghost small', textContent: 'Tap', onclick: () => transport.tap(uid) }));- }- if (!k) btns.append(el('button', { className: 'ghost small', textContent: 'Forget', onclick: () => forgetKey(uid) }));- const li = el('li', { className: [k ? '' : 'offline', k?.pressed ? 'pressed' : '', flashUid === uid ? 'flash' : ''].join(' ') },- el('div', {}, el('div', { className: 'name', textContent: keyName(uid) }),- el('div', { className: 'meta' }, `${where} · uid `, el('code', { textContent: uid }))),- el('span', { className: 'combo' + (combo ? '' : ' none'), textContent: combo || 'not assigned' }),- btns);- li.dataset.uid = uid;- list.append(li);- }+ for (const uid of [...online, ...offline].filter(matches)) list.append(keyCard(uid));flashUid = null;+ const any = online.length + offline.length > 0;$('#keys-empty').hidden = list.children.length > 0;- $('#keys-empty').textContent = transport- ? "No Keybits connected. Attach one to the Keyword's left, right or top edge."- : 'Connect to the Keyword to see its Keybits.';+ $('#keys-empty').textContent = q && any ? `No keys match "${q}".`+ : transport ? "No Keybits connected. Attach one to the Keyword's left, right or top edge."+ : 'Connect to the Keyword, or try Demo, to see its Keybits.';// Profiles- const sel = $('#profile-select');- sel.replaceChildren(...store.profiles.map((p) => el('option', { value: p.id, textContent: p.name, selected: p.id === store.active })));+ $('#profile-select').replaceChildren(...store.profiles.map((x, i) =>+ el('option', { value: x.id, textContent: x.name, title: i < 9 ? `${MOD_KEY}+${i + 1}` : '', selected: x.id === store.active })));$('#p-delete').disabled = store.profiles.length < 2;$('#p-apply').disabled = !transport;+ renderApps();++ // Undo/redo+ $('#btn-undo').disabled = !history.canUndo;+ $('#btn-undo').title = history.canUndo ? `Undo ${history.undoLabel} (${MOD_KEY}+Z)` : 'Nothing to undo';+ $('#btn-redo').disabled = !history.canRedo;+ $('#btn-redo').title = history.canRedo ? `Redo ${history.redoLabel}` : 'Nothing to redo';++ // Status pills+ const fwPill = $('#pill-fw');+ fwPill.hidden = !transport || !device.fw;+ fwPill.textContent = `Firmware ${device.fw}`;+ const b = device.battery;+ $('#pill-batt').hidden = !transport || !b;+ if (b) {+ $('#pill-batt .batt-fill').style.width = `${b.pct}%`;+ $('#pill-batt').classList.toggle('low', b.pct <= 15 && !b.charging);+ $('#pill-batt').classList.toggle('charging', b.charging);+ $('#pill-batt .batt-text').textContent = `${b.pct}%${b.charging ? ' charging' : b.usb ? ' on USB' : ''}`;+ }+ const appPill = $('#pill-app');+ appPill.hidden = !settings().perApp || !frontApp;+ if (frontApp) appPill.textContent = autoSwitched ? `${frontApp} → ${p.name}` : `App: ${frontApp}`;+ appPill.title = 'Per-app profiles are on (Settings)';++ pushState();}+function keyCard(uid) {+ const k = keys.get(uid);+ const m = entryOf(uid);+ const combo = comboFor(uid);+ const hold = holdLabel(m?.hold);+ const where = !k ? 'Not connected'+ : k.at ? SIDE_NAMES[k.at][0].toUpperCase() + SIDE_NAMES[k.at].slice(1)+ : k.via ? `Chained behind ${keyName(k.via)}${k.depth > 1 ? ` (${k.depth} hops)` : ''}` : 'Connected';+ const presses = store.stats[uid] || 0;++ const btns = el('div', { className: 'btns' });+ btns.append(el('button', { className: 'ghost small', textContent: 'Assign…', onclick: () => openAssign(uid) }));+ if (k && transport instanceof DemoTransport) {+ btns.append(el('button', { className: 'ghost small', textContent: 'Tap', title: 'Simulate a press', onclick: () => transport.tap(uid) }));+ }+ if (k && !k.via && can('flash') && k.flashing == null) {+ btns.append(el('button', {+ className: 'ghost small' + (outdated(k) ? ' attention' : ''), textContent: outdated(k) ? 'Update' : 'Reflash',+ title: outdated(k) ? `Keybit firmware v${k.v}, Keyword has v${device.kb}` : 'Reflash this Keybit', onclick: () => flashKey(uid),+ }));+ }+ if (!k && m && [...keys.keys()].some((u) => !Profiles.isMapped(entryOf(u)))) {+ btns.append(el('button', { className: 'ghost small', textContent: 'Move to…', title: 'Give this setup to a connected Keybit, e.g. after swapping one out', onclick: () => moveKey(uid) }));+ }+ if (!k) btns.append(el('button', { className: 'ghost small', textContent: 'Forget', onclick: () => forgetKey(uid) }));++ const kind = m?.host ? 'host' : m?.macro?.length ? 'macro' : '';+ const badges = el('span', { className: 'badges' },+ k?.v != null ? el('span', { className: 'badge ver' + (outdated(k) ? ' warn' : ''), textContent: `v${k.v}`, title: outdated(k) ? 'Firmware update available' : 'Keybit firmware' }) : null,+ kind === 'host' ? el('span', { className: 'badge', textContent: 'computer', title: 'Runs on this computer while the app is open' }) : null,+ kind === 'macro' ? el('span', { className: 'badge', textContent: 'macro' }) : null);++ const meta = el('div', { className: 'meta' },+ `${where} · `,+ el('button', { className: 'uid link', textContent: `…${uid.slice(-8)}`, title: `${uid}\nClick to copy`, onclick: () => copyUid(uid) }),+ presses ? ` · ${presses.toLocaleString()} press${presses === 1 ? '' : 'es'}` : '',+ k?.flashing != null ? el('span', { className: 'flashing', textContent: ` · Flashing ${k.flashing}%` }) : null);++ const li = el('li', { className: [k ? '' : 'offline', k?.pressed ? 'pressed' : '', flashUid === uid ? 'flash' : ''].join(' ') },+ el('div', { className: 'info' }, el('div', { className: 'name' }, keyName(uid), badges), meta),+ el('div', { className: 'actions-col' },+ el('span', { className: 'combo' + (combo ? '' : ' none'), textContent: combo || 'not assigned', title: combo }),+ hold ? el('span', { className: 'hold', textContent: `hold: ${hold}` }) : null),+ btns);+ li.dataset.uid = uid;+ li.addEventListener('dblclick', (e) => { if (!e.target.closest('button')) openAssign(uid); });+ return li;+}++function renderApps() {+ const p = activeProfile();+ const box = $('#apps');+ box.replaceChildren(...p.apps.map((a) => el('span', { className: 'chip' }, a,+ el('button', { className: 'chip-x', textContent: '×', title: `Stop using in ${a}`, onclick: () => mutate(`remove ${a}`, () => { p.apps = p.apps.filter((x) => x !== a); }, null) }))));+ $('#apps-hint').textContent = !settings().perApp+ ? 'Turn on "Switch profiles by the app in front" in Settings to use this.'+ : p.apps.length ? '' : 'Not tied to any app. Other profiles switch back to this one when you leave their app.';+}++let lastState = '';+function pushState() {+ if (!bridge) return;+ const s = {+ status: $('#status-text').textContent,+ profiles: store.profiles.map((p) => ({ id: p.id, name: p.name })),+ active: store.active,+ battery: transport && device.battery ? device.battery.pct : null,+ };+ const j = JSON.stringify(s);+ if (j !== lastState) { lastState = j; bridge.updateState(s); }+}++async function copyUid(uid) {+ try { await navigator.clipboard.writeText(uid); toast('UID copied'); } catch { toast(uid); }+}++// ---- Protocol handling ----+function handleLine(line) {lastRx = Date.now();log('<-', line);const msg = parseLine(line);switch (msg.type) {- case 'hello':- setStatus(`Connected over ${transport.label} · Keyword firmware ${msg.fw}`, 'connected');+ case 'hello': {+ const first = !device.fw;+ device = { ...device, fw: msg.fw, caps: msg.caps, kb: msg.kb };+ setStatus(`Connected over ${transport.label}`, 'connected');if (msg.proto !== 1) log('!!', `protocol ${msg.proto}, app expects 1`);+ if (first) {+ if (can('batt')) send(cmd.battery());+ applyProfile(true); // now that caps are known+ }break;+ }case 'sides':for (const [s, v] of Object.entries(msg.sides)) {sides[s] = v;@@ -259,33 +513,90 @@ function handleLine(line) {if (!v) for (const [uid, k] of keys) if (k.at === s) removeKey(uid);}break;- case 'keyAdd':- syncSeen?.add(msg.uid);- addKey(msg.uid, msg.at, false);+ case 'keyAdd': {+ const uid = resolveUid(msg.uid);+ syncSeen?.add(uid);+ addKey(uid, msg.at, msg.v, msg.via !== undefined ? { via: msg.via, depth: msg.depth } : null);+ break;+ }+ case 'keyRemove':+ removeKey(resolveUid(msg.uid));break;case 'keysEnd':if (syncSeen) for (const uid of [...keys.keys()]) if (!syncSeen.has(uid)) removeKey(uid);syncSeen = null;break;- case 'keyRemove':- removeKey(msg.uid);+ case 'press':+ onPress(resolveUid(msg.uid), msg.down);+ return;+ case 'battery': {+ const prev = device.battery;+ device.battery = { pct: msg.pct, charging: msg.charging, usb: msg.usb };+ if (prev && prev.pct > 15 && msg.pct <= 15 && !msg.charging) {+ toast(`Keyword battery low (${msg.pct}%)`, { error: true });+ notify('Keyword battery low', `${msg.pct}% left`);+ }break;- case 'press': {+ }+ case 'flashProgress': {const k = keys.get(msg.uid);- if (k) k.pressed = msg.down;- else addKey(msg.uid, null, false);- const li = document.querySelector(`#keys li[data-uid="${msg.uid}"]`);- if (li) { li.classList.toggle('pressed', msg.down); return; } // skip a full re-render+ if (k) k.flashing = msg.pct;break;}- case 'error':+ case 'ok':+ if (msg.what === 'FLASH' && msg.uid) {+ const uid = msg.uid.toUpperCase();+ const k = keys.get(uid);+ if (k) k.flashing = null;+ activity(`${keyName(uid)} reflashed`, 'add');+ toast(`${keyName(uid)} reflashed`);+ syncKeys();+ }+ break;+ case 'error': {log('!!', msg.message);- activity(`Keyword error: ${msg.message}`, 'remove');+ activity(`Keyword: ${msg.message}`, 'remove');+ if (/^flash/i.test(msg.message)) for (const k of keys.values()) k.flashing = null;break;+ }}render();}+let statsDirty = false;+let pressRender = null;+function onPress(uid, down) {+ const k = keys.get(uid);+ if (k) k.pressed = down;+ else addKey(uid, null, null);+ if (down) {+ store.stats[uid] = (store.stats[uid] || 0) + 1;+ statsDirty = true;+ const m = entryOf(uid);+ if (m?.host) runHost(m.host, uid);+ }+ // Cheap update instead of a full render on every press.+ const li = document.querySelector(`#keys li[data-uid="${uid}"]`);+ if (li && k) li.classList.toggle('pressed', down);+ const slot = document.querySelector(`.slot[data-uid="${uid}"]`);+ if (slot) slot.classList.toggle('pressed', down);+ if (!k) render();+ else if (down) { clearTimeout(pressRender); pressRender = setTimeout(render, 400); }+ if (assign.open && assignUid === uid && down) $('#assign-name').classList.add('blink');+}+setInterval(() => { if (statsDirty) { statsDirty = false; persist(); } }, 10000);++async function runHost(h, uid) {+ if (h.type === 'next-profile') return cycleProfile(1);+ if (h.type === 'profile') {+ if (store.profiles.some((p) => p.id === h.value)) switchTo(h.value, { manual: true });+ return;+ }+ if (!bridge) return toast(`${hostLabel(h)} (only in the bridge app)`);+ const r = await bridge.runHost(h);+ if (!r.ok) toast(`${keyName(uid)}: ${r.error}`, { error: true });+}+async function send(...lines) {if (!transport) return;for (const l of lines) {@@ -299,71 +610,177 @@ function syncKeys() {send(cmd.keys());}-function applyProfile() {- if (!transport) return;- send(...profileCommands(activeProfile().keys));- activity(`Sent profile "${activeProfile().name}" to the Keyword`);+function applyProfile(quiet) {+ if (!transport || !device.fw) return;+ send(...profileCommands(activeProfile().keys, caps()));+ if (!quiet) {+ activity(`Sent "${activeProfile().name}" to the Keyword`);+ toast(`Sent "${activeProfile().name}" to the Keyword`);+ }+}++// Programs one key after an edit. UNMAP first clears any old macro/hold.+function syncKey(uid) {+ const m = entryOf(uid);+ const c = caps();+ send(cmd.unmap(uid), ...(m ? entryCommands(uid, m, c) : []), cmd.save());}-async function connect(t) {- await disconnect();- setStatus(`Connecting over ${t.label}…`, 'busy');+function flashKey(uid) {+ const k = keys.get(uid);+ if (!k) return;+ k.flashing = 0;+ activity(`Reflashing ${keyName(uid)}…`);+ send(cmd.flash(uid));+ render();+}++// ---- Connecting ----++async function connect(t, { auto = false } = {}) {+ await disconnect({ quiet: true });+ setStatus(auto ? `Reconnecting over ${t.label}…` : `Connecting over ${t.label}…`, 'busy');const lines = new LineBuffer(handleLine);try {- await t.open((text) => lines.push(text), () => { log('!!', 'device disconnected'); disconnect(); });+ await t.open((text) => lines.push(text), () => onLinkLost(t));} catch (e) {- closeDialog(chooser);+ closeDialog($('#chooser'));+ if (auto) throw e;setStatus(e.name === 'NotFoundError' ? 'Not connected' : `Could not connect: ${e.message}`);- return;+ return false;}+ stopReconnect();transport = t;+ device = { fw: null, caps: new Set(), kb: null, battery: null };lastRx = Date.now();- setStatus(`Connected over ${t.label} · waiting for Keyword…`, 'busy');+ setStatus(`Connected over ${t.label} · waiting for the Keyword…`, 'busy');const demo = t instanceof DemoTransport;document.body.classList.toggle('demo', demo);$('#demo-hint').hidden = !demo;$('#btn-disconnect').hidden = false;activity(`Connected over ${t.label}`);+ if (!demo) { settings().lastConnection = t.identity(); persist(); }render();await send(cmd.hello(), cmd.sides());syncKeys();- applyProfile();timers = [setInterval(() => {send(cmd.sides());if (Date.now() - lastRx > STALE_MS) setStatus(`Connected over ${t.label} · no reply from the Keyword`, 'stale');}, POLL_MS),setInterval(syncKeys, KEYS_POLL_MS),+ setInterval(() => { if (can('batt')) send(cmd.battery()); }, BATT_POLL_MS),];+ return true;}-async function disconnect() {+async function disconnect({ quiet = false } = {}) {timers.forEach(clearInterval);timers = [];const t = transport;transport = null;if (t) {await t.close();- activity('Disconnected');+ if (!quiet) activity('Disconnected');}+ if (!quiet) stopReconnect();document.body.classList.remove('demo');$('#demo-hint').hidden = true;$('#btn-disconnect').hidden = true;keys.clear();sides = {};+ device = { fw: null, caps: new Set(), kb: null, battery: null };render();- setStatus('Not connected');+ if (!reconnect) setStatus('Not connected');+}++function onLinkLost(t) {+ if (transport !== t) return;+ log('!!', 'device disconnected');+ activity('Keyword disconnected', 'remove');+ notify('Keyword disconnected', settings().autoReconnect ? 'Trying to reconnect…' : '');+ disconnect({ quiet: true });+ if (settings().autoReconnect) startReconnect(t);+ else setStatus('Not connected');+}++// Retries with backoff. Serial waits for the port to come back; BLE re-dials the same device.+function startReconnect(t) {+ stopReconnect();+ reconnect = { tries: 0, timer: null, kind: t.kind, device: t.device };+ const attempt = async () => {+ if (!reconnect || transport) return;+ reconnect.tries++;+ setStatus(`Reconnecting… (try ${reconnect.tries})`, 'busy');+ try {+ if (reconnect.kind === 'ble' && reconnect.device) await connect(new BleTransport(reconnect.device), { auto: true });+ else if (reconnect.kind === 'serial') {+ const port = await findSerialPort();+ if (!port) throw new Error('port not back yet');+ await connect(new SerialTransport(port), { auto: true });+ }+ return;+ } catch (e) {+ log('!!', `reconnect: ${e.message}`);+ }+ if (!reconnect) return;+ if (reconnect.tries >= 20) { stopReconnect(); setStatus('Not connected · gave up reconnecting'); return; }+ reconnect.timer = setTimeout(attempt, Math.min(30000, 1000 * 2 ** Math.min(reconnect.tries, 5)));+ };+ reconnect.timer = setTimeout(attempt, 1000);+}+function stopReconnect() {+ if (reconnect?.timer) clearTimeout(reconnect.timer);+ reconnect = null;+}++async function findSerialPort() {+ const last = settings().lastConnection;+ if (!('serial' in navigator) || last?.kind !== 'serial') return null;+ const ports = await navigator.serial.getPorts();+ return ports.find((p) => {+ const i = p.getInfo?.() || {};+ return last.usbVendorId == null || (i.usbVendorId === last.usbVendorId && i.usbProductId === last.usbProductId);+ }) || null;+}++// On launch, quietly reconnect to the last Keyword if its permission is still granted.+async function autoConnectOnLaunch() {+ const last = settings().lastConnection;+ if (!settings().autoReconnect || !last || transport) return;+ try {+ if (last.kind === 'serial') {+ const port = await findSerialPort();+ if (port) await connect(new SerialTransport(port), { auto: true });+ } else if (last.kind === 'ble' && navigator.bluetooth?.getDevices) {+ const dev = (await navigator.bluetooth.getDevices()).find((d) => d.id === last.id);+ if (dev) await connect(new BleTransport(dev), { auto: true });+ }+ } catch (e) {+ log('!!', `auto-connect: ${e.message}`);+ setStatus('Not connected');+ }+}++// A Keyword plugged back in over USB reconnects straight away.+if ('serial' in navigator) {+ navigator.serial.addEventListener('connect', async () => {+ if (transport || !settings().autoReconnect || settings().lastConnection?.kind !== 'serial') return;+ const port = await findSerialPort();+ if (port) connect(new SerialTransport(port), { auto: true }).catch((e) => log('!!', e.message));+ });}// ---- Dialog helpers ----function closeDialog(d) { if (d.open) d.close(); }-function askText(title, value) {+function askText(title, value, suggestions = []) {const d = $('#prompt');$('#prompt-title').textContent = title;const input = $('#prompt-input');input.value = value || '';+ $('#prompt-list').replaceChildren(...suggestions.map((s) => el('option', { value: s })));return new Promise((resolve) => {const done = (v) => { closeDialog(d); resolve(v); };$('#prompt-ok').onclick = () => done(input.value.trim() || null);@@ -401,9 +818,9 @@ chooser.addEventListener('cancel', () => window.devicePicker?.pick(''));// ---- Assign dialog ----const assign = $('#assign');-const capture = $('#capture');let assignUid = null;-let draft = { mods: 0, key: 0, consumer: 0 };+let tab = 'shortcut';+let draft = null; // { mods, key, consumer, macro: [], host: {type, value}, hold: {mods, key, ms} }$('#assign-mods').append(...Hid.MODS.map((m) =>el('label', {}, el('input', { type: 'checkbox', value: m.bit }), Hid.modName(m, MAC))));@@ -412,168 +829,542 @@ $('#assign-key').append(el('option', { value: 'k:0', textContent: '(no key, modiel('optgroup', { label: 'Keys' }, ...Hid.KEYS.map((k) => el('option', { value: `k:${k.usage}`, textContent: k.label }))),el('optgroup', { label: 'Media' }, ...Hid.CONSUMER.map((c) => el('option', { value: `c:${c.usage}`, textContent: c.label }))));-const draftLabel = () => (draft.consumer ? Hid.consumerLabel(draft.consumer) : Hid.comboLabel(draft.mods, draft.key, MAC));-const draftEmpty = () => !draft.consumer && !draft.mods && !draft.key;+function setTab(t) {+ tab = t;+ $$('#assign .tab').forEach((b) => b.setAttribute('aria-selected', String(b.dataset.tab === t)));+ $$('#assign .tab-panel').forEach((p) => { p.hidden = p.dataset.panel !== t; });+ $('#assign-test').hidden = t !== 'host';+ $('#hold-box').hidden = t === 'host';+ showDraft();+ const focus = { shortcut: '#capture', macro: '#macro-capture', host: '#host-value' }[t];+ setTimeout(() => $(focus)?.focus(), 0);+}+$$('#assign .tab').forEach((b) => { b.onclick = () => setTab(b.dataset.tab); });++const shortcutLabel = () => (draft.consumer ? Hid.consumerLabel(draft.consumer) : Hid.comboLabel(draft.mods, draft.key, MAC));function showDraft() {- $('#assign-mods').querySelectorAll('input').forEach((c) => { c.checked = !!(draft.mods & (1 << c.value)); });+ // Shortcut tab+ $('#assign-mods').querySelectorAll('input').forEach((c) => { c.checked = !!(draft.mods & (1 << c.value)); c.disabled = !!draft.consumer; });$('#assign-key').value = draft.consumer ? `c:${draft.consumer}` : `k:${draft.key}`;- $('#capture-combo').textContent = draftLabel() || 'Press a key or shortcut…';+ $('#capture-combo').textContent = shortcutLabel() || 'Click here and press a key or shortcut…';++ // Macro tab+ const steps = $('#macro-steps');+ steps.replaceChildren(...draft.macro.map((st, i) => el('span', { className: 'chip' }, Hid.stepLabel(st, MAC),+ el('button', { className: 'chip-x', textContent: '×', title: 'Remove', onclick: (e) => { e.stopPropagation(); draft.macro.splice(i, 1); showDraft(); } }))));+ if (!draft.macro.length) steps.append(el('span', { className: 'hint', textContent: 'Click here and press keys to record…' }));+ const macroNote = [`${draft.macro.length}/${MAX_MACRO_STEPS} steps.`];+ if (device.fw && !can('macro')) macroNote.push("This Keyword's firmware doesn't support macros yet, so it won't be sent.");+ $('#macro-note').textContent = macroNote.join(' ');++ // Host tab+ const type = draft.host.type;+ $('#host-type').value = type;+ const needsValue = ['url', 'app', 'cmd'].includes(type);+ $('#host-value').hidden = !needsValue;+ $('#host-value').placeholder = { url: 'https://example.com or spotify:…', app: MAC ? 'App name, e.g. Spotify' : 'App or program, e.g. notepad', cmd: 'Shell command, e.g. open ~/Downloads' }[type] || '';+ $('#host-value').setAttribute('list', type === 'app' ? 'app-names' : '');+ if ($('#host-value').value !== draft.host.value && needsValue) $('#host-value').value = draft.host.value;+ $('#host-profile').hidden = type !== 'profile';+ $('#host-profile').replaceChildren(...store.profiles.map((p) => el('option', { value: p.id, textContent: p.name, selected: p.id === draft.host.value })));++ // Hold+ const hl = holdLabel(draft.hold);+ $('#hold-combo').textContent = hl || 'Click here and press what to send while held…';+ $('#hold-summary').textContent = hl ? `· ${hl}` : '';+ $('#hold-ms').value = draft.hold.ms || DEFAULT_HOLD_MS;+ $('#hold-note').textContent = device.fw && !can('hold')+ ? "This Keyword's firmware doesn't support hold actions yet, so it won't be sent."+ : 'A quick tap sends the main action; holding longer than this sends the hold action.';}+$('#assign-mods').addEventListener('change', () => {draft.mods = [...$('#assign-mods').querySelectorAll('input')].reduce((m, c) => m | (c.checked ? 1 << c.value : 0), 0);- draft.consumer = 0; // media keys can't take modifiersshowDraft();});$('#assign-key').addEventListener('change', (e) => {const [kind, usage] = e.target.value.split(':');- draft = kind === 'c' ? { mods: 0, key: 0, consumer: Number(usage) } : { ...draft, key: Number(usage), consumer: 0 };+ if (kind === 'c') Object.assign(draft, { mods: 0, key: 0, consumer: Number(usage) });+ else Object.assign(draft, { key: Number(usage), consumer: 0 });showDraft();});-function captureKey(e) {+// Key search: results are clickable chips; Enter picks the first.+function showSearch() {+ const q = $('#key-search').value;+ const res = q.trim() ? Hid.search(q).slice(0, 14) : [];+ $('#key-results').replaceChildren(...res.map((r) => el('button', {+ className: 'chip pick', textContent: r.label + (r.kind === 'c' ? ' ♪' : ''),+ onclick: () => pickSearch(r),+ })));+}+function pickSearch(r) {+ if (r.kind === 'c') Object.assign(draft, { mods: 0, key: 0, consumer: r.usage });+ else Object.assign(draft, { key: r.usage, consumer: 0 });+ $('#key-search').value = '';+ showSearch();+ showDraft();+}+$('#key-search').addEventListener('input', showSearch);+$('#key-search').addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); const r = Hid.search($('#key-search').value)[0]; if (r) pickSearch(r); }+});++// Capture boxes. Electron hands us every key (even Cmd+Q) while one is focused.+let captureTarget = null;+function onCaptured(e) {const r = Hid.fromEvent(e);- if (!r) return;- draft = r.consumer ? { mods: 0, key: 0, consumer: r.consumer } : { mods: r.mods, key: r.usage, consumer: 0 };+ if (!r || !captureTarget) return;+ if (captureTarget === 'shortcut') {+ if (r.consumer) Object.assign(draft, { mods: 0, key: 0, consumer: r.consumer });+ else Object.assign(draft, { mods: r.mods, key: r.usage, consumer: 0 });+ } else if (captureTarget === 'macro') {+ if (r.consumer || !r.usage) return; // wait for a real key; media keys can't go in a macro+ if (draft.macro.length >= MAX_MACRO_STEPS) return toast(`Macros hold up to ${MAX_MACRO_STEPS} steps`);+ draft.macro.push([r.mods, r.usage]);+ } else if (captureTarget === 'hold') {+ if (r.consumer) return;+ draft.hold = { ...draft.hold, mods: r.mods, key: r.usage };+ }showDraft();}-capture.addEventListener('keydown', (e) => { e.preventDefault(); e.stopPropagation(); captureKey(e); });-capture.addEventListener('focus', () => window.desktop?.setCapture(true));-capture.addEventListener('blur', () => window.desktop?.setCapture(false));-window.desktop?.onCaptureKey((k) => { if (k.type === 'keyDown') captureKey(k); });+for (const [id, target] of [['#capture', 'shortcut'], ['#macro-capture', 'macro'], ['#hold-capture', 'hold']]) {+ const box = $(id);+ box.addEventListener('keydown', (e) => { e.preventDefault(); e.stopPropagation(); onCaptured(e); });+ box.addEventListener('focus', () => { captureTarget = target; bridge?.setCapture(true); box.classList.add('listening'); });+ box.addEventListener('blur', () => { captureTarget = null; bridge?.setCapture(false); box.classList.remove('listening'); });+}+bridge?.onCaptureKey((k) => { if (k.type === 'keyDown') onCaptured(k); });++$('#macro-add-text').onclick = () => {+ const { steps, skipped } = Hid.textToSteps($('#macro-text').value);+ const room = MAX_MACRO_STEPS - draft.macro.length;+ draft.macro.push(...steps.slice(0, room));+ if (steps.length > room) toast(`Only ${room} more step${room === 1 ? '' : 's'} fit; the rest was cut`);+ if (skipped.length) toast(`Skipped characters with no US key: ${[...new Set(skipped)].join(' ')}`);+ $('#macro-text').value = '';+ showDraft();+};+$('#macro-text').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); $('#macro-add-text').click(); } });+$('#macro-clear').onclick = () => { draft.macro = []; showDraft(); };++$('#host-type').onchange = (e) => {+ draft.host = { type: e.target.value, value: e.target.value === 'profile' ? store.profiles[0].id : '' };+ $('#host-value').value = '';+ showDraft();+};+$('#host-value').oninput = (e) => { draft.host.value = e.target.value; };+$('#host-profile').onchange = (e) => { draft.host.value = e.target.value; };+$('#hold-ms').onchange = (e) => { draft.hold.ms = Math.min(2000, Math.max(50, Number(e.target.value) || DEFAULT_HOLD_MS)); };+$('#hold-clear').onclick = () => { draft.hold = { mods: 0, key: 0, ms: draft.hold.ms }; showDraft(); };function openAssign(uid) {assignUid = uid;- const m = activeProfile().keys[uid];- draft = { mods: m?.mods || 0, key: m?.key || 0, consumer: m?.consumer || 0 };+ const m = entryOf(uid) || {};+ draft = {+ mods: m.mods || 0, key: m.key || 0, consumer: m.consumer || 0,+ macro: (m.macro || []).map((s) => [...s]),+ host: m.host ? { ...m.host } : { type: 'url', value: '' },+ hold: m.hold ? { ...m.hold } : { mods: 0, key: 0, ms: DEFAULT_HOLD_MS },+ };$('#assign-name').textContent = keyName(uid);- $('#assign-label').value = m?.name || '';- $('#assign-clear').disabled = !m;- showDraft();+ $('#assign-name').classList.remove('blink');+ $('#assign-label').value = m.name || '';+ $('#assign-clear').disabled = !Profiles.isMapped(m) && !m.name;+ $('#key-search').value = '';+ $('#host-value').value = m.host?.value || '';+ $('#app-names').replaceChildren(...[...seenApps].sort().map((a) => el('option', { value: a })));+ $('#hold-box').open = hasHold(m);+ showSearch();assign.showModal();- capture.focus();+ setTab(m.host ? 'host' : m.macro?.length ? 'macro' : 'shortcut');}function closeAssign() {- window.desktop?.setCapture(false);+ bridge?.setCapture(false);closeDialog(assign);}-assign.addEventListener('close', () => window.desktop?.setCapture(false));+assign.addEventListener('close', () => bridge?.setCapture(false));$('#assign-cancel').onclick = closeAssign;++// The entry the dialog describes, for the current tab.+function draftEntry() {+ const name = $('#assign-label').value.trim();+ let e;+ if (tab === 'host') {+ const v = draft.host.type === 'profile' ? $('#host-profile').value : draft.host.type === 'next-profile' ? '' : $('#host-value').value.trim();+ e = { host: { type: draft.host.type, value: v } };+ } else if (tab === 'macro') e = draft.macro.length ? { macro: draft.macro } : { mods: 0, key: 0 };+ else e = draft.consumer ? { mods: 0, key: 0, consumer: draft.consumer } : { mods: draft.mods, key: draft.key };+ if (tab !== 'host' && (draft.hold.mods || draft.hold.key)) e.hold = { ...draft.hold };+ if (name) e.name = name;+ return Profiles.cleanEntry(e);+}+$('#assign-save').onclick = () => {const uid = assignUid;- const name = $('#assign-label').value.trim();+ const e = draftEntry();+ if (e.host && ['url', 'app', 'cmd'].includes(e.host.type) && !e.host.value) {+ toast('Fill in what to open or run first', { error: true });+ return $('#host-value').focus();+ }const p = activeProfile();- if (draftEmpty() && !name) delete p.keys[uid];- else p.keys[uid] = { ...draft, ...(name ? { name } : {}) };- if (!draft.consumer) delete p.keys[uid]?.consumer;- persist();- send(mapCommand(uid, draft) || cmd.unmap(uid), cmd.save());+ mutate(`assign ${keyName(uid)}`, () => {+ if (!Profiles.isMapped(e) && !e.name && !hasHold(e)) delete p.keys[uid];+ else p.keys[uid] = e;+ }, () => syncKey(uid));activity(`${keyName(uid)} → ${comboFor(uid) || 'nothing'}`);closeAssign();- render();};$('#assign-clear').onclick = () => {- delete activeProfile().keys[assignUid];- persist();- send(cmd.unmap(assignUid), cmd.save());+ const uid = assignUid;+ mutate(`unassign ${keyName(uid)}`, () => { delete activeProfile().keys[uid]; }, () => syncKey(uid));closeAssign();- render();+ toast(`Unassigned ${keyName(uid)}`, { undo: true });+};+$('#assign-test').onclick = () => {+ const e = draftEntry();+ if (e.host) runHost(e.host, assignUid);};+// Hands an offline key's setup to a connected, unassigned Keybit.+async function moveKey(uid) {+ const free = [...keys.keys()].filter((u) => !Profiles.isMapped(entryOf(u)));+ if (!free.length) return;+ let target = free[0];+ if (free.length > 1) {+ const labels = free.map((u) => `${keys.get(u).at ? SIDE_NAMES[keys.get(u).at] : 'connected'} (…${u.slice(-4)})`);+ const pick = await askText(`Move "${keyName(uid)}" to which Keybit?`, labels[0], labels);+ if (!pick) return;+ target = free[labels.indexOf(pick)] ?? free.find((u) => pick.includes(u.slice(-4)));+ if (!target) return;+ }+ const name = keyName(uid);+ mutate(`move ${name}`, () => {+ const p = activeProfile();+ p.keys[target] = p.keys[uid];+ delete p.keys[uid];+ }, () => syncKey(target));+ toast(`Moved ${name} to the ${SIDE_NAMES[keys.get(target)?.at] || 'connected'} Keybit`, { undo: true });+}+function forgetKey(uid) {- delete activeProfile().keys[uid];- persist();- render();+ const name = keyName(uid);+ mutate(`forget ${name}`, () => { delete activeProfile().keys[uid]; }, null);+ toast(`Forgot ${name}`, { undo: true });}-// ---- Profile buttons ----+// ---- Profiles -----function switchTo(id) {- store.active = id;- persist();+function switchTo(id, { manual = true, record = false } = {}) {+ if (!store.profiles.some((p) => p.id === id)) return;+ if (id === store.active) return;+ const doIt = () => { store.active = id; };+ if (record) mutate('switch profile', doIt, null);+ else { doIt(); persist(); render(); }+ if (manual) { manualActive = id; autoSwitched = false; }+ applyProfile(true);+ if (manual) activity(`Switched to "${activeProfile().name}"`);render();- applyProfile();}++function cycleProfile(dir) {+ const i = store.profiles.findIndex((p) => p.id === store.active);+ const next = store.profiles[(i + dir + store.profiles.length) % store.profiles.length];+ switchTo(next.id);+ toast(`Profile: ${next.name}`);+}+$('#profile-select').onchange = (e) => switchTo(e.target.value);-$('#p-new').onclick = async () => {+$('#p-new').onclick = newProfileFlow;+async function newProfileFlow() {const name = await askText('New profile name', `Profile ${store.profiles.length + 1}`);if (!name) return;const p = Profiles.newProfile(name);- store.profiles.push(p);- switchTo(p.id);-};+ mutate(`new profile ${name}`, () => { store.profiles.push(p); store.active = p.id; });+ manualActive = p.id;+}$('#p-dup').onclick = async () => {const cur = activeProfile();const name = await askText('Name for the copy', `${cur.name} copy`);if (!name) return;- const p = Profiles.newProfile(name, JSON.parse(JSON.stringify(cur.keys)));- store.profiles.push(p);- switchTo(p.id);+ const p = Profiles.newProfile(name, cur.keys);+ mutate(`duplicate ${cur.name}`, () => { store.profiles.push(p); store.active = p.id; });+ manualActive = p.id;};$('#p-rename').onclick = async () => {- const name = await askText('Rename profile', activeProfile().name);- if (!name) return;- activeProfile().name = name;- persist();- render();+ const cur = activeProfile();+ const name = await askText('Rename profile', cur.name);+ if (!name || name === cur.name) return;+ mutate(`rename ${cur.name}`, () => { cur.name = name; }, null);};$('#p-delete').onclick = () => {if (store.profiles.length < 2) return;- if (!confirm(`Delete profile "${activeProfile().name}"?`)) return;- store.profiles = store.profiles.filter((p) => p.id !== store.active);- switchTo(store.profiles[0].id);+ const cur = activeProfile();+ mutate(`delete ${cur.name}`, () => {+ store.profiles = store.profiles.filter((p) => p.id !== cur.id);+ store.active = store.profiles[0].id;+ });+ manualActive = store.active;+ toast(`Deleted "${cur.name}"`, { undo: true });};-$('#p-export').onclick = async () => {- const p = activeProfile();- const text = Profiles.exportProfile(p);- if (window.desktop) {- if (await window.desktop.exportProfile(p.name, text)) activity(`Exported "${p.name}"`);- return;- }- const a = el('a', { href: URL.createObjectURL(new Blob([text], { type: 'application/json' })), download: `${p.name}.keyword.json` });++async function saveText(name, text) {+ if (bridge) return bridge.saveFile(name, text);+ const a = el('a', { href: URL.createObjectURL(new Blob([text], { type: 'application/json' })), download: name });a.click();URL.revokeObjectURL(a.href);-};-function importText(text) {- try {- const p = Profiles.importProfile(text);- store.profiles.push(p);- activity(`Imported "${p.name}"`);- switchTo(p.id);- } catch (e) {- activity(`Import failed: ${e.message}`, 'remove');- }+ return true;}-$('#p-import').onclick = async () => {- if (window.desktop) {- const text = await window.desktop.importProfile();- if (text != null) importText(text);- return;+async function exportCurrent() {+ const p = activeProfile();+ if (await saveText(`${p.name}.keyword.json`, Profiles.exportProfile(p))) activity(`Exported "${p.name}"`);+}+async function exportAll() {+ if (await saveText('Keyword profiles.keyword.json', Profiles.exportLibrary(store.profiles))) activity(`Exported ${store.profiles.length} profiles`);+}+$('#p-export').onclick = exportCurrent;+$('#set-export-all').onclick = exportAll;++function importTexts(files) {+ const added = [];+ for (const f of files) {+ try { added.push(...Profiles.importProfiles(f.text)); } catch (e) { toast(`${f.name}: ${e.message}`, { error: true }); }}- const input = el('input', { type: 'file', accept: '.json,application/json' });- input.onchange = async () => { if (input.files[0]) importText(await input.files[0].text()); };+ if (!added.length) return;+ // A shared profile could run anything on this computer, so ask before keeping commands.+ const risky = added.flatMap((p) => Object.values(p.keys).filter((e) => e.host && ['cmd', 'app'].includes(e.host.type)).map((e) => e.host));+ if (risky.length) {+ const list = risky.slice(0, 8).map((h) => `• ${h.type === 'cmd' ? 'Run' : 'Open'}: ${h.value}`).join('\n');+ const keep = confirm(`These profiles run things on this computer when a key is pressed:\n\n${list}${risky.length > 8 ? '\n…' : ''}\n\nKeep them? Cancel removes those actions and imports the rest.`);+ if (!keep) for (const p of added) for (const [u, e] of Object.entries(p.keys)) if (e.host && ['cmd', 'app'].includes(e.host.type)) delete p.keys[u];+ }+ // Keep names unique so the menu stays readable.+ const names = new Set(store.profiles.map((p) => p.name));+ for (const p of added) {+ let n = p.name, i = 2;+ while (names.has(n)) n = `${p.name} (${i++})`;+ p.name = n;+ names.add(n);+ }+ mutate(`import ${added.length} profile${added.length === 1 ? '' : 's'}`, () => {+ store.profiles.push(...added);+ store.active = added[0].id;+ });+ manualActive = store.active;+ toast(`Imported ${added.map((p) => `"${p.name}"`).join(', ')}`, { undo: true });+}+async function importFlow() {+ if (bridge) return importTexts(await bridge.openFiles());+ const input = el('input', { type: 'file', accept: '.json,application/json', multiple: true });+ input.onchange = async () => importTexts(await Promise.all([...input.files].map(async (f) => ({ name: f.name, text: await f.text() }))));input.click();+}+$('#p-import').onclick = importFlow;+$('#p-apply').onclick = () => applyProfile(false);++// Drag a profile file onto the window to import it.+document.addEventListener('dragover', (e) => { e.preventDefault(); document.body.classList.add('dropping'); });+document.addEventListener('dragleave', (e) => { if (!e.relatedTarget) document.body.classList.remove('dropping'); });+document.addEventListener('drop', async (e) => {+ e.preventDefault();+ document.body.classList.remove('dropping');+ const files = [...(e.dataTransfer?.files || [])].filter((f) => /\.json$/i.test(f.name));+ if (files.length) importTexts(await Promise.all(files.map(async (f) => ({ name: f.name, text: await f.text() }))));+});++// Apps for per-app switching+$('#p-add-app').onclick = async () => {+ const suggestions = [...seenApps].filter((a) => !SELF_APPS.has(a.toLowerCase())).sort();+ const name = await askText('Use this profile in which app?', '', suggestions);+ if (!name) return;+ const p = activeProfile();+ if (p.apps.some((a) => a.toLowerCase() === name.toLowerCase())) return;+ const other = Profiles.profileForApp(store.profiles, name);+ mutate(`add ${name}`, () => {+ if (other) other.apps = other.apps.filter((a) => a.toLowerCase() !== name.toLowerCase());+ p.apps.push(name);+ }, null);+ if (other) toast(`Moved ${name} from "${other.name}"`);+ if (!settings().perApp) toast('Turn on per-app switching in Settings for this to take effect');};-$('#p-apply').onclick = applyProfile;-// ---- Connection buttons ----+function onFrontApp(name) {+ if (!name || SELF_APPS.has(name.toLowerCase())) return;+ seenApps.add(name);+ frontApp = name;+ if (!settings().perApp) return render();+ const target = Profiles.profileForApp(store.profiles, name);+ if (target) {+ if (target.id !== store.active) {+ switchTo(target.id, { manual: false });+ autoSwitched = true;+ activity(`${name} → "${target.name}"`);+ }+ } else if (autoSwitched && manualActive && manualActive !== store.active) {+ switchTo(manualActive, { manual: false });+ autoSwitched = false;+ }+ render();+}+bridge?.onFrontApp(onFrontApp);++// ---- Library -----$('#btn-usb').onclick = () => {+function openLibrary() {+ const known = [...new Set([...keys.keys(), ...Object.keys(activeProfile().keys)])];+ const uids = Templates.orderUids(known, (u) => keys.get(u)?.at);+ const list = $('#library-list');+ list.replaceChildren(...Templates.TEMPLATES.map((t) => {+ const preview = t.build(MAC).map((a) => a.name || actionLabel(a)).join(' · ');+ return el('li', {},+ el('div', {}, el('b', { textContent: t.name }), el('p', { className: 'hint', textContent: t.description }),+ el('p', { className: 'preview', textContent: preview })),+ el('div', { className: 'btns' },+ el('button', { className: 'small', textContent: 'New profile', onclick: () => useTemplate(t, uids, true) }),+ el('button', { className: 'ghost small', textContent: 'Apply here', title: 'Overwrite these keys in the current profile', onclick: () => useTemplate(t, uids, false) })));+ }));+ $('#library').showModal();+}+function useTemplate(t, uids, asNew) {+ if (!uids.length) return toast('Attach a Keybit (or try Demo) first, so there are keys to assign', { error: true });+ const { keys: k, apps, used, total } = Templates.applyTemplate(t, uids, MAC);+ if (asNew) {+ const p = Profiles.newProfile(t.name, k, apps);+ mutate(`add ${t.name}`, () => { store.profiles.push(p); store.active = p.id; });+ manualActive = p.id;+ } else {+ const p = activeProfile();+ mutate(`apply ${t.name}`, () => { Object.assign(p.keys, k); });+ }+ closeDialog($('#library'));+ toast(`${t.name}: ${used} of ${total} actions assigned${used < total ? ' (attach more Keybits for the rest)' : ''}`, { undo: true });+}+$('#p-library').onclick = openLibrary;+$('#library-close').onclick = () => closeDialog($('#library'));++// ---- Settings ----++function applySettings() {+ const s = settings();+ if (s.theme === 'system') delete document.documentElement.dataset.theme;+ else document.documentElement.dataset.theme = s.theme;+ bridge?.applySettings({ theme: s.theme, closeToTray: s.closeToTray, launchAtLogin: s.launchAtLogin, perApp: s.perApp });+ if (!s.perApp) { autoSwitched = false; }+}+function openSettings() {+ const s = settings();+ $('#set-theme').value = s.theme;+ for (const k of ['autoReconnect', 'perApp', 'notifications', 'closeToTray', 'launchAtLogin']) $(`#set-${k}`).checked = !!s[k];+ $('#settings').showModal();+}+$('#set-theme').onchange = (e) => { settings().theme = e.target.value; persist(); applySettings(); };+for (const k of ['autoReconnect', 'perApp', 'notifications', 'closeToTray', 'launchAtLogin']) {+ $(`#set-${k}`).onchange = async (e) => {+ settings()[k] = e.target.checked;+ if (k === 'notifications' && e.target.checked && 'Notification' in window && Notification.permission === 'default') {+ try { await Notification.requestPermission(); } catch {}+ }+ persist();+ applySettings();+ render();+ };+}+$('#set-reset-stats').onclick = () => { store.stats = {}; persist(); render(); toast('Press counts reset'); };+$('#set-data').onclick = () => bridge?.openDataFolder();+$('#set-data').hidden = !bridge;+$('#settings-close').onclick = () => closeDialog($('#settings'));+$('#btn-settings').onclick = openSettings;++function toggleTheme() {+ const dark = document.documentElement.dataset.theme === 'dark'+ || (!document.documentElement.dataset.theme && matchMedia('(prefers-color-scheme: dark)').matches);+ settings().theme = dark ? 'light' : 'dark';+ persist();+ applySettings();+}+$('#btn-theme').onclick = toggleTheme;++// ---- Buttons, menu and shortcuts ----++const connectUsb = () => {if (!('serial' in navigator)) return setStatus('Web Serial is not available here');connect(new SerialTransport());};-$('#btn-ble').onclick = () => {+const connectBle = () => {if (!('bluetooth' in navigator)) return setStatus('Web Bluetooth is not available here');connect(new BleTransport());};+$('#btn-usb').onclick = connectUsb;+$('#btn-ble').onclick = connectBle;$('#btn-demo').onclick = () => connect(new DemoTransport());$('#btn-disconnect').onclick = () => disconnect();+$('#btn-undo').onclick = undo;+$('#btn-redo').onclick = redo;+$('#activity-clear').onclick = () => $('#activity').replaceChildren();+$('#key-filter').addEventListener('input', render);-document.querySelectorAll('.board .slot').forEach((slot) => {+$$('.board .slot').forEach((slot) => {slot.addEventListener('click', () => {if (transport instanceof DemoTransport) transport.toggle(slot.dataset.side);+ else if (slot.dataset.uid) openAssign(slot.dataset.uid);});});-storage.load().then((s) => { store = Profiles.normalizeStore(s); render(); });+const inTextField = () => {+ const a = document.activeElement;+ return a && (a.tagName === 'TEXTAREA' || (a.tagName === 'INPUT' && !['checkbox', 'radio'].includes(a.type)));+};+const anyDialogOpen = () => $$('dialog').some((d) => d.open);++function onMenu(command, arg) {+ if (captureTarget) return; // the recorder owns the keyboard+ switch (command) {+ case 'undo': if (inTextField()) document.execCommand('undo'); else if (!anyDialogOpen()) undo(); break;+ case 'redo': if (inTextField()) document.execCommand('redo'); else if (!anyDialogOpen()) redo(); break;+ case 'settings': openSettings(); break;+ case 'import': importFlow(); break;+ case 'export': exportCurrent(); break;+ case 'export-all': exportAll(); break;+ case 'connect-usb': connectUsb(); break;+ case 'connect-ble': connectBle(); break;+ case 'disconnect': disconnect(); break;+ case 'profile': switchTo(arg); break;+ case 'next-profile': cycleProfile(1); break;+ case 'prev-profile': cycleProfile(-1); break;+ case 'new-profile': newProfileFlow(); break;+ case 'library': openLibrary(); break;+ case 'apply': applyProfile(false); break;+ case 'toggle-theme': toggleTheme(); break;+ case 'find': $('#key-filter').focus(); $('#key-filter').select(); break;+ }+}+bridge?.onMenu(onMenu);++// In a plain browser (no Electron menu) handle the same shortcuts here.+if (!bridge) {+ document.addEventListener('keydown', (e) => {+ const mod = MAC ? e.metaKey : e.ctrlKey;+ if (!mod || captureTarget) return;+ const k = e.key.toLowerCase();+ if (k === 'z' && !e.shiftKey) { if (!inTextField()) { e.preventDefault(); onMenu('undo'); } }+ else if ((k === 'z' && e.shiftKey) || k === 'y') { if (!inTextField()) { e.preventDefault(); onMenu('redo'); } }+ else if (k === 'f') { e.preventDefault(); onMenu('find'); }+ else if (/^[1-9]$/.test(k) && store.profiles[k - 1]) { e.preventDefault(); onMenu('profile', store.profiles[k - 1].id); }+ });+}++// ---- Start ----++storage.load().then(async (s) => {+ store = Profiles.normalizeStore(s);+ manualActive = store.active;+ applySettings();+ render();+ if (bridge) {+ const info = await bridge.appInfo();+ $('#set-about').textContent = `Keyword Monitor ${info.version} · ${info.platform}`;+ }+ autoConnectOnLaunch();+});render();diff --git a/app/renderer/index.html b/app/renderer/index.htmlindex 2424a84..492aec3 100644--- a/app/renderer/index.html+++ b/app/renderer/index.html@@ -11,15 +11,25 @@<header><h1>Keyword Monitor</h1><div class="actions">- <button id="btn-usb">USB serial</button>- <button id="btn-ble">Bluetooth</button>+ <button id="btn-usb" title="Connect over USB (Cmd/Ctrl+U)">USB serial</button>+ <button id="btn-ble" title="Connect over Bluetooth (Cmd/Ctrl+B)">Bluetooth</button><button id="btn-demo" class="ghost">Demo</button><button id="btn-disconnect" class="ghost" hidden>Disconnect</button>+ <span class="sep"></span>+ <button id="btn-undo" class="icon ghost" title="Undo" aria-label="Undo">↶</button>+ <button id="btn-redo" class="icon ghost" title="Redo" aria-label="Redo">↷</button>+ <button id="btn-theme" class="icon ghost" title="Toggle light/dark (Cmd/Ctrl+Shift+L)" aria-label="Toggle theme">◐</button>+ <button id="btn-settings" class="icon ghost" title="Settings" aria-label="Settings">⚙</button></div></header><div id="status" class="status"><span class="dot"></span><span id="status-text">Not connected</span>+ <span class="pills">+ <span id="pill-app" class="pill" hidden></span>+ <span id="pill-fw" class="pill" hidden></span>+ <span id="pill-batt" class="pill batt" hidden><span class="batt-icon"><span class="batt-fill"></span></span><span class="batt-text"></span></span>+ </span></div><main>@@ -27,21 +37,22 @@<div class="board" aria-label="Keyword and its sides"><div class="slot slot-T" data-side="T"><span class="slot-label"></span></div><div class="slot slot-L" data-side="L"><span class="slot-label"></span></div>- <div class="keyword">Keyword</div>+ <div class="keyword"><span>Keyword</span><small id="board-profile"></small></div><div class="slot slot-R" data-side="R"><span class="slot-label"></span></div></div><p id="demo-hint" class="hint center" hidden>Demo: click a side to attach or remove a Keybit.</p>- <h2>Keys</h2>+ <div class="section-head">+ <h2>Keys</h2>+ <input id="key-filter" type="search" placeholder="Find a key…" aria-label="Find a key">+ </div><ul id="keys" class="keys"></ul>- <p id="keys-empty" class="hint">No Keybits connected. Attach one to the Keyword's left, right or top edge.</p>+ <p id="keys-empty" class="hint"></p></section><section class="col side"><h2>Profile</h2>- <div class="profile-row">- <select id="profile-select" aria-label="Active profile"></select>- </div>+ <select id="profile-select" aria-label="Active profile"></select><div class="btn-row"><button id="p-new" class="ghost small">New</button><button id="p-dup" class="ghost small">Duplicate</button>@@ -49,13 +60,22 @@<button id="p-delete" class="ghost small">Delete</button></div><div class="btn-row">+ <button id="p-library" class="ghost small">Library…</button><button id="p-import" class="ghost small">Import…</button><button id="p-export" class="ghost small">Export…</button>- <button id="p-apply" class="small">Send to Keyword</button></div>- <p id="profile-note" class="hint">Profiles save automatically on this computer.</p>+ <button id="p-apply" class="small">Send to Keyword</button>++ <div id="apps-box" class="apps-box">+ <div class="apps-head"><b>Use automatically in</b> <button id="p-add-app" class="link">+ Add app</button></div>+ <div id="apps" class="chips"></div>+ <p id="apps-hint" class="hint small-text"></p>+ </div>- <h2>Activity</h2>+ <div class="section-head">+ <h2>Activity</h2>+ <button id="activity-clear" class="link">Clear</button>+ </div><ul id="activity" class="activity"></ul></section></main>@@ -65,6 +85,8 @@<pre id="log"></pre></details>+ <div id="toasts" class="toasts" aria-live="polite"></div>+<dialog id="chooser"><h2 id="chooser-title">Choose a device</h2><ul id="chooser-list"></ul>@@ -72,26 +94,97 @@<div class="dialog-actions"><button id="chooser-cancel" class="ghost">Cancel</button></div></dialog>- <dialog id="assign">+ <dialog id="assign" class="wide"><h2>Assign <span id="assign-name"></span></h2>- <div id="capture" class="capture" tabindex="0">- <span id="capture-combo">Press a key or shortcut…</span>+ <div class="tabs" role="tablist">+ <button role="tab" data-tab="shortcut" class="tab">Key or shortcut</button>+ <button role="tab" data-tab="macro" class="tab">Macro</button>+ <button role="tab" data-tab="host" class="tab">Computer action</button>+ </div>++ <div class="tab-panel" data-panel="shortcut">+ <div id="capture" class="capture" tabindex="0"><span id="capture-combo"></span></div>+ <input id="key-search" type="search" placeholder="Search keys: volume, f13, page down…" aria-label="Search keys">+ <div id="key-results" class="chips results"></div>+ <div id="assign-mods" class="mods"></div>+ <select id="assign-key" aria-label="Key"></select>+ </div>++ <div class="tab-panel" data-panel="macro">+ <p class="hint">Keys are tapped in order. Click the box and press keys to record, or type text to add it.</p>+ <div id="macro-capture" class="capture macro" tabindex="0"><span id="macro-steps" class="chips"></span></div>+ <div class="row">+ <input id="macro-text" placeholder="Text to type, e.g. your email">+ <button id="macro-add-text" class="ghost small">Add text</button>+ <button id="macro-clear" class="ghost small">Clear</button>+ </div>+ <p id="macro-note" class="hint small-text"></p></div>- <p class="hint">Or build it by hand, for keys your OS keeps for itself:</p>- <div id="assign-mods" class="mods"></div>- <select id="assign-key" aria-label="Key"></select>++ <div class="tab-panel" data-panel="host">+ <p class="hint">Runs on this computer while Keyword Monitor is open. The Keyword sends no key for it.</p>+ <select id="host-type" aria-label="Action">+ <option value="url">Open a website or link</option>+ <option value="app">Open an app</option>+ <option value="cmd">Run a command</option>+ <option value="next-profile">Switch to the next profile</option>+ <option value="profile">Switch to a profile</option>+ </select>+ <input id="host-value" aria-label="Value">+ <select id="host-profile" aria-label="Profile"></select>+ <datalist id="app-names"></datalist>+ </div>++ <details id="hold-box" class="hold-box">+ <summary>When held <span id="hold-summary" class="hint"></span></summary>+ <div id="hold-capture" class="capture small" tabindex="0"><span id="hold-combo"></span></div>+ <div class="row">+ <label class="inline">Hold for <input id="hold-ms" type="number" min="50" max="2000" step="10" value="200"> ms</label>+ <button id="hold-clear" class="ghost small">No hold action</button>+ </div>+ <p id="hold-note" class="hint small-text"></p>+ </details>+<label class="field">Name <input id="assign-label" maxlength="40" placeholder="optional, e.g. Mute mic"></label><div class="dialog-actions"><button id="assign-clear" class="ghost">Unassign</button>+ <button id="assign-test" class="ghost">Test</button><span class="spacer"></span><button id="assign-cancel" class="ghost">Cancel</button><button id="assign-save">Save</button></div></dialog>+ <dialog id="library" class="wide">+ <h2>Profile library</h2>+ <p class="hint">Ready-made layouts. Actions go to your Keybits in order: left, top edge, right.</p>+ <ul id="library-list" class="library"></ul>+ <div class="dialog-actions"><button id="library-close" class="ghost">Close</button></div>+ </dialog>++ <dialog id="settings">+ <h2>Settings</h2>+ <label class="field">Theme+ <select id="set-theme"><option value="system">Match system</option><option value="light">Light</option><option value="dark">Dark</option></select>+ </label>+ <label class="check"><input type="checkbox" id="set-autoReconnect"> Reconnect to the last Keyword automatically</label>+ <label class="check"><input type="checkbox" id="set-perApp"> Switch profiles by the app in front</label>+ <label class="check"><input type="checkbox" id="set-notifications"> Notify when Keybits connect or disconnect</label>+ <label class="check"><input type="checkbox" id="set-closeToTray"> Keep running in the menu bar / tray when closed</label>+ <label class="check"><input type="checkbox" id="set-launchAtLogin"> Open at login</label>+ <div class="btn-row">+ <button id="set-export-all" class="ghost small">Export all profiles…</button>+ <button id="set-reset-stats" class="ghost small">Reset press counts</button>+ <button id="set-data" class="ghost small">Open data folder</button>+ </div>+ <p id="set-about" class="hint small-text"></p>+ <div class="dialog-actions"><button id="settings-close">Done</button></div>+ </dialog>+<dialog id="prompt"><h2 id="prompt-title"></h2>- <input id="prompt-input" maxlength="40">+ <input id="prompt-input" maxlength="80" list="prompt-list">+ <datalist id="prompt-list"></datalist><div class="dialog-actions"><button id="prompt-cancel" class="ghost">Cancel</button><button id="prompt-ok">OK</button>@@ -101,6 +194,7 @@<script src="protocol.js"></script><script src="hid.js"></script><script src="profiles.js"></script>+ <script src="templates.js"></script><script src="app.js"></script></body></html>diff --git a/app/renderer/style.css b/app/renderer/style.cssindex e702edb..7edaa31 100644--- a/app/renderer/style.css+++ b/app/renderer/style.css@@ -5,37 +5,41 @@--muted: #6b7280;--line: #d6d9df;--accent: #2f6fde;+ --accent-text: #ffffff;--on: #1f9d63;--on-soft: #d9f2e6;- --warn: #c98a12;+ --warn: #b7790a;+ --warn-soft: #fbefd6;+ --danger: #c2413a;--off: #9aa1ad;--keyword: #2a2f3a;--keyword-text: #f0f2f5;--press-soft: #e3ecfb;- --accent-text: #ffffff;+ --shadow: 0 6px 24px rgba(15, 20, 30, 0.14);color-scheme: light;}+/* Dark tokens, used when the system is dark (unless forced light) or when forced dark. */@media (prefers-color-scheme: dark) {- :root {- --bg: #14161a;- --panel: #1d2026;- --text: #e8eaee;- --muted: #9099a8;- --line: #333844;- --accent: #6c9cf0;- --on: #3cc287;- --on-soft: #18392b;- --warn: #e0a83a;- --off: #5d6472;- --keyword: #3a4150;- --keyword-text: #f0f2f5;- --press-soft: #1d2c47;- --accent-text: #0d1220;+ :root:not([data-theme="light"]) {+ --bg: #14161a; --panel: #1d2026; --text: #e8eaee; --muted: #9099a8; --line: #333844;+ --accent: #6c9cf0; --accent-text: #0d1220; --on: #3cc287; --on-soft: #18392b;+ --warn: #e0a83a; --warn-soft: #3a2e15; --danger: #ef6b63; --off: #5d6472;+ --keyword: #3a4150; --keyword-text: #f0f2f5; --press-soft: #1d2c47;+ --shadow: 0 6px 24px rgba(0, 0, 0, 0.5);color-scheme: dark;}}+:root[data-theme="dark"] {+ --bg: #14161a; --panel: #1d2026; --text: #e8eaee; --muted: #9099a8; --line: #333844;+ --accent: #6c9cf0; --accent-text: #0d1220; --on: #3cc287; --on-soft: #18392b;+ --warn: #e0a83a; --warn-soft: #3a2e15; --danger: #ef6b63; --off: #5d6472;+ --keyword: #3a4150; --keyword-text: #f0f2f5; --press-soft: #1d2c47;+ --shadow: 0 6px 24px rgba(0, 0, 0, 0.5);+ color-scheme: dark;+}* { box-sizing: border-box; }+[hidden] { display: none !important; }body {margin: 0;font: 14px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;@@ -45,121 +49,179 @@ body {flex-direction: column;min-height: 100vh;}+body.dropping::after {+ content: "Drop to import profiles";+ position: fixed; inset: 12px; border: 3px dashed var(--accent); border-radius: 14px;+ display: grid; place-items: center; font-size: 18px; font-weight: 600; color: var(--accent);+ background: color-mix(in srgb, var(--bg) 85%, transparent); z-index: 50; pointer-events: none;+}header {- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- flex-wrap: wrap;- padding: 14px 20px;- border-bottom: 1px solid var(--line);- background: var(--panel);+ display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;+ padding: 12px 20px; border-bottom: 1px solid var(--line); background: var(--panel);}h1 { font-size: 16px; margin: 0; font-weight: 600; }-.actions { display: flex; gap: 8px; flex-wrap: wrap; }+.actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }+.actions .sep { width: 1px; height: 22px; background: var(--line); margin: 0 2px; }button {- font: inherit;- padding: 6px 14px;- border-radius: 6px;- border: 1px solid var(--accent);- background: var(--accent);- color: var(--accent-text);- cursor: pointer;+ font: inherit; padding: 6px 14px; border-radius: 6px; cursor: pointer;+ border: 1px solid var(--accent); background: var(--accent); color: var(--accent-text);}button.ghost { background: transparent; color: var(--text); border-color: var(--line); }-button:disabled { opacity: 0.5; cursor: default; }+button.ghost:hover:not(:disabled) { border-color: var(--muted); }+button.icon { padding: 4px 9px; font-size: 16px; line-height: 1.2; }+button.small { padding: 4px 10px; font-size: 13px; }+button.link { background: none; border: none; padding: 0; color: var(--accent); font-size: 13px; }+button.attention { border-color: var(--warn); color: var(--warn); }+button:disabled { opacity: 0.45; cursor: default; }+button:focus-visible, select:focus-visible, input:focus-visible, .capture:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }-.status { display: flex; align-items: center; gap: 8px; padding: 10px 20px; color: var(--muted); }-.status .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--off); }+.status { display: flex; align-items: center; gap: 8px; padding: 10px 20px; color: var(--muted); flex-wrap: wrap; }+.status .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--off); flex: none; }.status.connected .dot { background: var(--on); }.status.stale .dot, .status.busy .dot { background: var(--warn); }+.status.busy .dot { animation: pulse 1s ease-in-out infinite alternate; }+@keyframes pulse { to { opacity: 0.3; } }+.pills { margin-left: auto; display: flex; gap: 6px; flex-wrap: wrap; }+.pill { border: 1px solid var(--line); border-radius: 999px; padding: 1px 10px; font-size: 12px; background: var(--panel); display: inline-flex; align-items: center; gap: 6px; }+.batt-icon { width: 20px; height: 10px; border: 1.5px solid currentColor; border-radius: 2px; position: relative; display: inline-block; }+.batt-icon::after { content: ""; position: absolute; right: -4px; top: 2px; width: 2px; height: 4px; background: currentColor; border-radius: 0 1px 1px 0; }+.batt-fill { position: absolute; left: 1px; top: 1px; bottom: 1px; max-width: calc(100% - 2px); background: var(--on); border-radius: 1px; }+.batt.low { color: var(--danger); border-color: var(--danger); }+.batt.low .batt-fill { background: var(--danger); }+.batt.charging .batt-fill { background: var(--accent); }-main { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) 280px; gap: 24px; padding: 20px; align-items: start; }-@media (max-width: 760px) { main { grid-template-columns: 1fr; } }+main { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 24px; padding: 8px 20px 20px; align-items: start; }+@media (max-width: 780px) { main { grid-template-columns: 1fr; } }.col { display: flex; flex-direction: column; gap: 12px; min-width: 0; }-.col.side { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px; }-h2 { font-size: 13px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); margin: 8px 0 0; font-weight: 600; }+.col.side { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px; gap: 10px; }+h2 { font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 6px 0 0; font-weight: 600; }+.section-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }+.section-head input { max-width: 220px; }.center { text-align: center; }-.board { align-self: center; margin: 8px 0 4px; }-button.small { padding: 4px 10px; font-size: 13px; }-.btn-row { display: flex; gap: 6px; flex-wrap: wrap; }+.hint { color: var(--muted); margin: 0; }+.small-text { font-size: 12px; }+.btn-row, .row { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }+.row input { flex: 1; min-width: 140px; }select, input { font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--line); border-radius: 6px; padding: 5px 8px; width: 100%; }--.keys { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }-.keys li { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; align-items: center; transition: border-color 0.1s, background 0.1s; }-.keys li.offline { opacity: 0.55; }-.keys li.pressed { border-color: var(--accent); background: var(--press-soft); }-.keys li.flash { animation: flash 1.2s ease-out; }-@keyframes flash { from { border-color: var(--on); box-shadow: 0 0 0 3px var(--on-soft); } to { box-shadow: 0 0 0 0 transparent; } }-.keys .name { font-weight: 600; }-.keys .meta { color: var(--muted); font-size: 12px; }-.keys .meta code { font-family: ui-monospace, Menlo, monospace; }-.keys .combo { justify-self: end; font-family: ui-monospace, Menlo, monospace; font-size: 13px; background: var(--bg); border: 1px solid var(--line); border-radius: 5px; padding: 2px 8px; }-.keys .combo.none { color: var(--muted); font-family: inherit; border-style: dashed; }-.keys .btns { grid-column: 2; display: flex; gap: 6px; justify-content: flex-end; }--.activity { list-style: none; margin: 0; padding: 0; max-height: 220px; overflow: auto; font-size: 13px; display: flex; flex-direction: column; gap: 4px; }-.activity li { display: flex; gap: 8px; }-.activity time { color: var(--muted); font-variant-numeric: tabular-nums; flex: none; }-.activity .add { color: var(--on); }-.activity .remove { color: var(--warn); }--.slot-label { font-size: 12px; text-align: center; padding: 2px; word-break: break-word; }--.capture { border: 2px dashed var(--accent); border-radius: 8px; padding: 18px; text-align: center; font-size: 18px; font-family: ui-monospace, Menlo, monospace; margin-bottom: 8px; outline: none; }-.capture:focus { background: var(--press-soft); }-.mods { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 6px 0 8px; font-size: 13px; }-.mods label { display: flex; gap: 4px; align-items: center; }-.mods input { width: auto; }-.field { display: flex; flex-direction: column; gap: 4px; margin-top: 10px; font-size: 13px; color: var(--muted); }-.spacer { flex: 1; }-.dialog-actions { gap: 8px; }+input[type="number"] { width: 80px; }+input[type="checkbox"] { width: auto; }/* Keyword in the middle, Keybit slots left, right and above. */.board {- --u: clamp(56px, 13vw, 96px);- --gap: 6px;- display: grid;+ --u: clamp(64px, 13vw, 104px);+ display: grid; align-self: center; margin: 8px 0 0; gap: 6px;grid-template-columns: var(--u) calc(var(--u) * 2) var(--u);grid-template-rows: var(--u) var(--u);- gap: var(--gap);}.keyword {- grid-column: 2; grid-row: 2;- background: var(--keyword);- color: var(--keyword-text);- border-radius: 8px;- display: grid; place-items: center;- font-weight: 600;+ grid-column: 2; grid-row: 2; background: var(--keyword); color: var(--keyword-text); border-radius: 8px;+ display: flex; flex-direction: column; align-items: center; justify-content: center; font-weight: 600; gap: 2px;}+.keyword small { font-weight: 400; opacity: 0.7; font-size: 11px; max-width: 90%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.slot-T { grid-column: 2; grid-row: 1; width: var(--u); justify-self: center; }.slot-L { grid-column: 1; grid-row: 2; }.slot-R { grid-column: 3; grid-row: 2; }.slot {- border: 2px dashed var(--line);- border-radius: 8px;- display: grid; place-items: center;- color: transparent;- transition: background 0.15s, border-color 0.15s;+ border: 2px dashed var(--line); border-radius: 8px; display: grid; place-items: center; color: transparent;+ transition: background 0.15s, border-color 0.15s, transform 0.08s;}-.slot.present { border: 2px solid var(--on); background: var(--on-soft); color: var(--on); font-weight: 600; }+.slot.present { border: 2px solid var(--on); background: var(--on-soft); color: var(--on); font-weight: 600; cursor: pointer; }+.slot.pressed { transform: translateY(2px); border-color: var(--accent); background: var(--press-soft); color: var(--accent); }.demo .slot { cursor: pointer; }.demo .slot:hover { border-color: var(--accent); }+.slot-label { font-size: 12px; text-align: center; padding: 3px; word-break: break-word; overflow: hidden; max-height: 100%; }+.keys { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }+.keys li {+ background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px;+ display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 12px; align-items: center;+ transition: border-color 0.1s, background 0.1s;+}+.keys li.offline { opacity: 0.55; }+.keys li.pressed { border-color: var(--accent); background: var(--press-soft); }+.keys li.flash { animation: flash 1.2s ease-out; }+@keyframes flash { from { border-color: var(--on); box-shadow: 0 0 0 3px var(--on-soft); } to { box-shadow: 0 0 0 0 transparent; } }+.keys .name { font-weight: 600; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }+.keys .meta { color: var(--muted); font-size: 12px; }+.keys .meta .uid { font-family: ui-monospace, Menlo, monospace; color: var(--muted); font-size: 12px; }+.keys .flashing { color: var(--accent); }+.actions-col { display: flex; flex-direction: column; align-items: flex-end; gap: 2px; min-width: 0; }+.keys .combo {+ font-family: ui-monospace, Menlo, monospace; font-size: 13px; background: var(--bg); border: 1px solid var(--line);+ border-radius: 5px; padding: 2px 8px; max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+.keys .combo.none { color: var(--muted); font-family: inherit; border-style: dashed; }+.keys .hold { font-size: 11px; color: var(--muted); font-family: ui-monospace, Menlo, monospace; }+.keys .btns { grid-column: 1 / -1; display: flex; gap: 6px; justify-content: flex-end; }+.badges { display: inline-flex; gap: 4px; }+.badge { font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; padding: 1px 6px; border-radius: 999px; border: 1px solid var(--line); color: var(--muted); }+.badge.ver { text-transform: none; }+.badge.warn { border-color: var(--warn); color: var(--warn); background: var(--warn-soft); }-.hint { color: var(--muted); margin: 0; }+.apps-box { border-top: 1px solid var(--line); padding-top: 10px; display: flex; flex-direction: column; gap: 6px; }+.apps-head { display: flex; justify-content: space-between; align-items: center; font-size: 13px; }+.chips { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; }+.chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 999px; background: var(--bg); border: 1px solid var(--line); font-size: 12px; font-family: ui-monospace, Menlo, monospace; }+.chip-x { background: none; border: none; color: var(--muted); padding: 0 0 0 2px; font-size: 13px; line-height: 1; }+.chip.pick { cursor: pointer; color: var(--text); font-family: inherit; }+.chip.pick:hover { border-color: var(--accent); }+.results:empty { display: none; }++.activity { list-style: none; margin: 0; padding: 0; max-height: 240px; overflow: auto; font-size: 13px; display: flex; flex-direction: column; gap: 4px; }+.activity li { display: flex; gap: 8px; }+.activity time { color: var(--muted); font-variant-numeric: tabular-nums; flex: none; }+.activity .add { color: var(--on); }+.activity .remove { color: var(--warn); }.log { border-top: 1px solid var(--line); background: var(--panel); padding: 8px 20px; }.log summary { cursor: pointer; color: var(--muted); }.log pre { max-height: 160px; overflow: auto; margin: 8px 0 0; font: 12px/1.4 ui-monospace, Menlo, monospace; white-space: pre-wrap; }-dialog { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); color: var(--text); width: min(420px, 90vw); padding: 18px; }+.toasts { position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; z-index: 40; width: max-content; max-width: calc(100vw - 32px); }+.toast { background: var(--keyword); color: var(--keyword-text); padding: 8px 14px; border-radius: 8px; box-shadow: var(--shadow); display: flex; gap: 14px; align-items: center; transition: opacity 0.3s, transform 0.3s; animation: toast-in 0.2s ease-out; }+.toast.error { background: var(--danger); color: #fff; }+.toast .link { color: inherit; text-decoration: underline; font-weight: 600; }+.toast.out { opacity: 0; transform: translateY(6px); }+@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } }++dialog { border: 1px solid var(--line); border-radius: 12px; background: var(--panel); color: var(--text); width: min(440px, 92vw); padding: 18px; box-shadow: var(--shadow); }+dialog.wide { width: min(600px, 94vw); }dialog::backdrop { background: rgba(0, 0, 0, 0.4); }-dialog h2 { font-size: 15px; margin: 0 0 10px; }+dialog h2 { font-size: 15px; margin: 0 0 12px; text-transform: none; letter-spacing: 0; color: var(--text); }+dialog > * + * { margin-top: 8px; }#chooser-list { list-style: none; margin: 0; padding: 0; max-height: 280px; overflow: auto; }#chooser-list button { width: 100%; text-align: left; background: transparent; color: var(--text); border: 1px solid var(--line); margin-bottom: 6px; display: flex; flex-direction: column; }#chooser-list button.likely { border-color: var(--on); }#chooser-list small { color: var(--muted); }-.dialog-actions { display: flex; justify-content: flex-end; margin-top: 10px; }+.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }+.spacer { flex: 1; }+#assign-name.blink { animation: blink 0.4s; }+@keyframes blink { 50% { color: var(--accent); } }++.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--line); }+.tab { background: none; border: none; border-bottom: 2px solid transparent; border-radius: 0; color: var(--muted); padding: 6px 10px; }+.tab[aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); font-weight: 600; }+.tab-panel { display: flex; flex-direction: column; gap: 8px; padding-top: 10px; }++.capture { border: 2px dashed var(--line); border-radius: 8px; padding: 16px; text-align: center; font-size: 17px; font-family: ui-monospace, Menlo, monospace; outline: none; cursor: text; min-height: 58px; display: flex; align-items: center; justify-content: center; }+.capture.listening { border-color: var(--accent); background: var(--press-soft); }+.capture.small { font-size: 14px; padding: 10px; min-height: 42px; }+.capture.macro { justify-content: flex-start; font-size: 13px; padding: 10px; }+.capture .hint { font-family: inherit; }+.mods { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: 13px; }+.mods label { display: flex; gap: 4px; align-items: center; }+.field { display: flex; flex-direction: column; gap: 4px; margin-top: 10px; font-size: 13px; color: var(--muted); }+.check { display: flex; gap: 8px; align-items: center; margin: 8px 0; }+.inline { display: inline-flex; gap: 6px; align-items: center; font-size: 13px; }+.hold-box { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; margin-top: 12px; }+.hold-box summary { cursor: pointer; font-size: 13px; font-weight: 600; }+.hold-box[open] summary { margin-bottom: 8px; }+.hold-box > * + * { margin-top: 8px; }++.library { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; max-height: 60vh; overflow: auto; }+.library li { border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; display: flex; gap: 12px; align-items: center; justify-content: space-between; }+.library li p { margin: 2px 0 0; }+.library .preview { font-size: 12px; color: var(--muted); font-family: ui-monospace, Menlo, monospace; }+.library .btns { display: flex; flex-direction: column; gap: 6px; flex: none; }