Skip to content

A truly modular keyboard

C

app: put chained Keybits exactly where they say they are, turned the right way

Nathan6e7e65e28fe2
diff --git a/app/src/renderer/src/components/Board.tsx b/app/src/renderer/src/components/Board.tsx
index b947616..129a30b 100644
--- a/app/src/renderer/src/components/Board.tsx
+++ b/app/src/renderer/src/components/Board.tsx
@@ -108,6 +108,13 @@ export function Board() {
)}
>
<span className="line-clamp-2">{label}</span>
+ {p.rot !== undefined && present && (
+ // A notch on the Keybit's own N side, so its turn shows.
+ <span
+ aria-hidden
+ className={clsx('absolute rounded-full bg-on opacity-60', ['top-1 left-1/2 h-1 w-4 -translate-x-1/2', 'top-1/2 right-1 h-4 w-1 -translate-y-1/2', 'bottom-1 left-1/2 h-1 w-4 -translate-x-1/2', 'top-1/2 left-1 h-4 w-1 -translate-y-1/2'][p.rot])}
+ />
+ )}
</button>
);
};
diff --git a/app/src/renderer/src/controller.ts b/app/src/renderer/src/controller.ts
index 08ac9eb..cc0e35e 100644
--- a/app/src/renderer/src/controller.ts
+++ b/app/src/renderer/src/controller.ts
@@ -12,6 +12,7 @@ import {
type OtaTarget, type Transport,
} from './lib/transports.ts';
import type { Entry, HostAction, Profile, Settings, Side } from './lib/types.ts';
+import type { Compass } from './lib/layout.ts';
import {
activeProfileOf, emptyDevice, initialOta, useApp, type ActivityTone, type AppState, type KeyState, type OtaState,
} from './store.ts';
@@ -168,7 +169,10 @@ function resolveUid(uid: string): string {
let highlightTimer: ReturnType<typeof setTimeout> | undefined;
-function addKey(uid: string, at: Side | null, v: number | null, relay: { via: string | null; depth: number | null } | null) {
+function addKey(
+ uid: string, at: Side | null, v: number | null, relay: { via: string | null; depth: number | null } | null,
+ where: { face?: Compass | null; parent?: string | null; pside?: Compass | null } = {},
+) {
const s = get();
const known = s.keys[uid];
// Seen in full for the first time: carry over a setup saved under its short UID.
@@ -192,6 +196,9 @@ function addKey(uid: string, at: Side | null, v: number | null, relay: { via: st
flashing: known?.flashing ?? null,
via: relay?.via ? resolveUid(relay.via) : known?.via ?? null,
depth: relay?.depth ?? known?.depth ?? null,
+ face: where.face ?? known?.face ?? null,
+ parent: where.parent ? resolveUid(where.parent) : known?.parent ?? null,
+ pside: where.pside ?? known?.pside ?? null,
backwards: known?.backwards ?? null,
};
set((st) => ({ keys: { ...st.keys, [uid]: next } }));
@@ -285,7 +292,8 @@ function handleLine(line: string) {
case 'keyAdd': {
const uid = resolveUid(msg.uid);
syncSeen?.add(uid);
- addKey(uid, msg.at, msg.v, msg.via !== undefined ? { via: msg.via ?? null, depth: msg.depth ?? null } : null);
+ addKey(uid, msg.at, msg.v, msg.via !== undefined ? { via: msg.via ?? null, depth: msg.depth ?? null } : null,
+ { face: msg.face, parent: msg.parent, pside: msg.pside });
break;
}
case 'keyRemove':
diff --git a/app/src/renderer/src/lib/layout.ts b/app/src/renderer/src/lib/layout.ts
index e897e93..b11633e 100644
--- a/app/src/renderer/src/lib/layout.ts
+++ b/app/src/renderer/src/lib/layout.ts
@@ -25,13 +25,23 @@ export interface Placed {
present?: boolean;
/** Placed by a guess (chained Keybits until the firmware says where they are). */
estimated?: boolean;
+ /** Its turn in clockwise quarter turns, when known. */
+ rot?: number;
}
+/** A Keybit's own sides. */
+export type Compass = 'N' | 'E' | 'S' | 'W';
+
/** What layout() needs to know about a Keybit. */
export interface LayoutKey {
at: Side | null;
via: string | null;
depth: number | null;
+ /** v11: its own side facing the Keyword or the Keybit it hangs off. */
+ face?: Compass | null;
+ /** v11: the Keybit it hangs off (null for one on the Keyword), and that one's side it's on. */
+ parent?: string | null;
+ pside?: Compass | null;
}
type Cell = [number, number];
@@ -46,40 +56,34 @@ const OUT: Record<Side, Cell> = { L: [-1, 0], T: [0, -1], R: [1, 0] };
*/
const OTHER: Partial<Record<Side, Side>> = { L: 'T', T: 'L' };
const NEXT: Cell[] = [[0, -1], [-1, 0], [1, 0], [0, 1]];
+/** A Keybit's own sides as steps, the usual way up. */
+const DIR: Record<Compass, Cell> = { N: [0, -1], E: [1, 0], S: [0, 1], W: [-1, 0] };
const key = ([x, y]: Cell) => `${x},${y}`;
+/** v turned clockwise by r quarter turns (screen y points down). */
+const turn = ([x, y]: Cell, r: number): Cell => (r % 4 === 0 ? [x, y] : turn([-y, x], r - 1));
+/** The turn that points a Keybit's side f the way of d, or null. */
+const turnFor = (f: Compass, d: Cell): number | null => {
+ for (let r = 0; r < 4; r++) { const [x, y] = turn(DIR[f], r); if (x === d[0] && y === d[1]) return r; }
+ return null;
+};
-/**
- * Lays out the board. A Keybit touching the Keyword goes in its side's slot;
- * when two report the same side, the second goes on the side it could also
- * be on. A chained one is only known by the Keybit it came through and how
- * many hops out it is, so until the firmware reports where it is, it's
- * estimated: on a free cell next to the Keybit one hop in, picking the cell
- * touching the most Keybits (so a block of Keybits stays a block), then
- * straight out. One whose route is unknown goes in a row under the Keyword.
- */
-export function layout(
+/** One way to place everything, and how many Keybits it couldn't place exactly. */
+function place(
keys: Record<string, LayoutKey>,
- sides: Partial<Record<Side, boolean>>,
- /** The side the user put an L/T Keybit on, by UID. */
- prefer: Record<string, Side> = {},
-): Placed[] {
+ direct: [string, LayoutKey][],
+ bySide: Partial<Record<Side, string>>,
+) {
const cells = new Map<string, string>([[key([0, 0]), 'keyword']]);
const at: Record<string, Cell> = {};
+ const rot: Record<string, number> = {};
const sideOf: Record<string, Side> = {};
-
- const direct = Object.entries(keys).filter(([, k]) => k.at).sort(([a], [b]) => a.localeCompare(b));
- const bySide: Partial<Record<Side, string>> = {};
- // The user's choices first, so they win their side.
- direct.sort(([a], [b]) => Number(!!prefer[b]) - Number(!!prefer[a]));
- for (const [uid, k] of direct) {
- const options = [k.at!, OTHER[k.at!]].filter(Boolean) as Side[];
- if (options.includes(prefer[uid])) options.unshift(prefer[uid]);
- const s = options.find((o) => !bySide[o]) ?? null;
- if (!s) continue; // no side left for it; it still shows in the key list
- bySide[s] = uid;
+ for (const [s, uid] of Object.entries(bySide) as [Side, string][]) {
sideOf[uid] = s;
at[uid] = SLOT[s];
+ const f = keys[uid].face;
+ const r = f ? turnFor(f, [-OUT[s][0], -OUT[s][1]]) : null;
+ if (r !== null) rot[uid] = r;
}
// The Keyword's own side slots are only for Keybits touching it, and its
// bottom has the USB port.
@@ -89,12 +93,35 @@ export function layout(
const chained = Object.entries(keys)
.filter(([, k]) => !k.at)
.sort(([a, ka], [b, kb]) => (ka.depth ?? 99) - (kb.depth ?? 99) || a.localeCompare(b));
+ const exact = new Set<string>();
+ let misses = 0;
+
+ // First what the Keybits report: the side of its parent each one is on,
+ // and its own side facing that parent, which gives its turn as well.
+ for (const [uid, k] of chained) {
+ const p = k.parent;
+ if (!p || !k.pside || !k.face || !at[p] || rot[p] === undefined) continue;
+ const d = turn(DIR[k.pside], rot[p]);
+ const c: Cell = [at[p][0] + d[0], at[p][1] + d[1]];
+ const r = turnFor(k.face, [-d[0], -d[1]]);
+ if (cells.has(key(c)) || r === null) { misses++; continue; }
+ at[uid] = c;
+ rot[uid] = r;
+ cells.set(key(c), uid);
+ exact.add(uid);
+ }
+
+ // Then a guess for the rest: a free cell next to the Keybit one hop in,
+ // the one touching the most Keybits (so a block stays a block), then
+ // straight out. One whose route is unknown goes in a row under the Keyword.
const hop: Record<string, Cell> = {}; // `${root uid}:${depth}` -> a cell at that hop
+ for (const [uid, k] of chained) if (exact.has(uid) && k.via && k.depth) hop[`${k.via}:${k.depth}`] ??= at[uid];
const loose: string[] = [];
for (const [uid, k] of chained) {
+ if (exact.has(uid)) continue;
const rootSide = k.via ? sideOf[k.via] : undefined;
if (!rootSide || !k.depth) { loose.push(uid); continue; }
- const from = hop[`${k.via}:${k.depth - 1}`] ?? at[k.via!];
+ const from = (k.parent && at[k.parent]) || hop[`${k.via}:${k.depth - 1}`] || at[k.via!];
const out = OUT[rootSide];
const free = NEXT.map(([dx, dy]): Cell => [from[0] + dx, from[1] + dy]).filter((c) => !cells.has(key(c)));
if (!free.length) { loose.push(uid); continue; }
@@ -108,16 +135,61 @@ export function layout(
cells.set(key(free[0]), uid);
hop[`${k.via}:${k.depth}`] ??= free[0];
}
+ return { at, rot, exact, loose, chained, misses };
+}
+
+/**
+ * Lays out the board. A Keybit touching the Keyword goes in its side's slot;
+ * when two report the same side, the second goes on the side it could also
+ * be on, and if the Keybits chained to them only fit one way round, that way.
+ * A chained Keybit on v11 says which side of which Keybit it's on and which
+ * way it's turned, so it goes exactly there. Older ones are estimated (dashed).
+ */
+export function layout(
+ keys: Record<string, LayoutKey>,
+ sides: Partial<Record<Side, boolean>>,
+ /** The side the user put an L/T Keybit on, by UID. */
+ prefer: Record<string, Side> = {},
+): Placed[] {
+ const direct = Object.entries(keys).filter(([, k]) => k.at).sort(([a], [b]) => a.localeCompare(b));
+ // The user's choices first, so they win their side.
+ direct.sort(([a], [b]) => Number(!!prefer[b]) - Number(!!prefer[a]));
+
+ // Every way the Keybits that could be on the left or the top can be
+ // shared out (at most 2^3), the user's way first; keep the first one
+ // the chained Keybits fit around exactly.
+ const assign = (flips: number) => {
+ const bySide: Partial<Record<Side, string>> = {};
+ let bit = 0;
+ for (const [uid, k] of direct) {
+ const options = [k.at!, OTHER[k.at!]].filter(Boolean) as Side[];
+ if (options.includes(prefer[uid])) options.unshift(prefer[uid]);
+ if (options.length > 1 && (flips >> bit++) & 1) options.reverse();
+ const s = options.find((o) => !bySide[o]);
+ if (s) bySide[s] = uid; // no side left: it still shows in the key list
+ }
+ return bySide;
+ };
+ const ambiguous = direct.filter(([, k]) => OTHER[k.at!]).length;
+ let best = place(keys, direct, assign(0));
+ let bySide = assign(0);
+ for (let flips = 1; best.misses && flips < 1 << Math.min(ambiguous, 3); flips++) {
+ const tryIt = place(keys, direct, assign(flips));
+ if (tryIt.misses < best.misses) { best = tryIt; bySide = assign(flips); }
+ }
+ const { at, rot, exact, loose, chained } = best;
const px = ([x, y]: Cell) => ({ x: x * STEP, y: y * STEP, w: TILE, h: TILE });
const out: Placed[] = [{ id: 'keyword', kind: 'keyword', ...px([0, 0]) }];
for (const s of ['L', 'T', 'R'] as Side[]) {
const uid = bySide[s];
- out.push(uid ? { id: uid, kind: 'keybit', side: s, uid, ...px(SLOT[s]) }
+ out.push(uid ? { id: uid, kind: 'keybit', side: s, uid, rot: rot[uid], ...px(SLOT[s]) }
// Something there the Keyword hasn't named yet; not a Keybit that's just drawn elsewhere.
: { id: `slot-${s}`, kind: 'slot', side: s, present: !!sides[s] && !direct.some(([, k]) => k.at === s), ...px(SLOT[s]) });
}
- for (const [uid] of chained) if (at[uid]) out.push({ id: uid, kind: 'keybit', uid, estimated: true, ...px(at[uid]) });
+ for (const [uid] of chained) {
+ if (at[uid] && !loose.includes(uid)) out.push({ id: uid, kind: 'keybit', uid, rot: rot[uid], estimated: !exact.has(uid), ...px(at[uid]) });
+ }
loose.forEach((uid, i) => out.push({ id: uid, kind: 'keybit', uid, estimated: true, ...px([i - 1, 2]) }));
return out;
}
diff --git a/app/src/renderer/src/lib/protocol.ts b/app/src/renderer/src/lib/protocol.ts
index 8793496..2c2661d 100644
--- a/app/src/renderer/src/lib/protocol.ts
+++ b/app/src/renderer/src/lib/protocol.ts
@@ -1,6 +1,7 @@
// Keyword host protocol: newline-terminated ASCII lines, the same over USB CDC and BLE.
// See PROTOCOL.md for the full description.
import type { Entry, Side, Step } from './types.ts';
+import type { Compass } from './layout.ts';
export const SIDES: readonly Side[] = ['L', 'R', 'T'];
@@ -164,7 +165,10 @@ export function profileCommands(keys: Record<string, Entry>, caps: ReadonlySet<s
export type Message =
| { type: 'hello'; fw: string; proto: number; caps: Set<string>; kb: number | null }
| { type: 'sides'; sides: Partial<Record<Side, boolean>> }
- | { type: 'keyAdd'; uid: string; at: Side | null; v: number | null; via?: string | null; depth?: number | null }
+ | {
+ type: 'keyAdd'; uid: string; at: Side | null; v: number | null; via?: string | null; depth?: number | null;
+ face?: Compass | null; parent?: string | null; pside?: Compass | null;
+ }
| { type: 'keyRemove'; uid: string }
| { type: 'keysEnd' }
| { type: 'press'; uid: string; down: boolean }
@@ -181,6 +185,7 @@ export type Message =
| { type: 'unknown'; line: string };
const isSide = (s: string | undefined): s is Side => SIDES.includes(s as Side);
+const isCompass = (s: string | undefined): s is Compass => s === 'N' || s === 'E' || s === 'S' || s === 'W';
/** Parses one line from the Keyword. Anything unrecognised comes back as {type: 'unknown'}. */
export function parseLine(line: string): Message {
@@ -212,6 +217,10 @@ export function parseLine(line: string): Message {
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 } : {}),
+ // v11: its own side facing the Keyword or its parent, and for a chained one
+ // the parent (low 32 bits of its UID) and that Keybit's side it's on.
+ ...(isCompass(f.face) ? { face: f.face } : {}),
+ ...(f.parent && isUid(f.parent) && isCompass(f.pside) ? { parent: f.parent.toUpperCase(), pside: f.pside } : {}),
};
case 'KEY-':
if (!uid) break;
diff --git a/app/src/renderer/src/lib/transports.ts b/app/src/renderer/src/lib/transports.ts
index 60bc00d..1607701 100644
--- a/app/src/renderer/src/lib/transports.ts
+++ b/app/src/renderer/src/lib/transports.ts
@@ -169,9 +169,12 @@ export class DemoTransport implements Transport {
private emit(line: string) { setTimeout(() => this.onText?.(line + '\n'), 20); }
private battLine() { return `BATT pct=${this.battery} chg=0 usb=0`; }
private sidesLine() { return 'SIDES ' + SIDES.map((s) => `${s}=${this.present[s] ? 1 : 0}`).join(' '); }
- private keyLine(s: Side) { return `KEY+ uid=${this.uids[s]} at=${s} v=${this.versions[s]}`; }
+ private keyLine(s: Side) { return `KEY+ uid=${this.uids[s]} at=${s} v=${this.versions[s]} face=${({ L: 'E', R: 'W', T: 'S' } as const)[s]}`; }
private chainedLine() {
- return `KEY+ uid=${this.chained} at=X via=${this.uids.R} depth=2 v=3\nKEY+ uid=${this.chained2} at=X via=${this.uids.R} depth=3 v=3`;
+ // Like v11 firmware: each says which side of which Keybit it's on and which way it faces it.
+ const r = this.uids.R.slice(-8);
+ return `KEY+ uid=${this.chained} at=X via=${this.uids.R} depth=2 parent=${r} pside=N face=S\n`
+ + `KEY+ uid=${this.chained2} at=X via=${this.uids.R} depth=3 parent=${this.chained} pside=E face=N`;
}
/** Attaches or removes the Keybit on a side. */
diff --git a/app/src/renderer/src/store.ts b/app/src/renderer/src/store.ts
index 8708e9b..d8b9bf1 100644
--- a/app/src/renderer/src/store.ts
+++ b/app/src/renderer/src/store.ts
@@ -3,6 +3,7 @@ import { create } from 'zustand';
import type { PickerList } from '../../shared/bridge';
import { normalizeStore } from './lib/profiles.ts';
import type { TransportKind } from './lib/transports.ts';
+import type { Compass } from './lib/layout.ts';
import type { Side, Store } from './lib/types.ts';
export interface KeyState {
@@ -12,6 +13,12 @@ export interface KeyState {
flashing: number | null;
via: string | null;
depth: number | null;
+ // v11 Keybits say where they are: their own side facing the Keyword or the
+ // Keybit they hang off (parent, null for one on the Keyword), and which
+ // side of that Keybit they're on. Null until known.
+ face: Compass | null;
+ parent: string | null;
+ pside: Compass | null;
// Its own sides (N/E/S/W) where another Keybit is on backwards, '?' when only
// known to be one of them, null when none.
backwards: string | null;
diff --git a/app/test/layout.test.ts b/app/test/layout.test.ts
index 6578109..c7ae9b3 100644
--- a/app/test/layout.test.ts
+++ b/app/test/layout.test.ts
@@ -55,3 +55,31 @@ test('chained Keybits never share a cell, and an unknown route still shows', ()
assert.strictEqual(new Set(cells).size, cells.length);
assert.ok(at(items, 'X'));
});
+
+test('v11 Keybits go exactly where they say, turned the way they say', () => {
+ // A on the left, the usual way round (its E side to the Keyword).
+ // B hangs off A's N side facing it with S: straight up from A, same turn.
+ // C hangs off B's N side but faces it with W: turned, straight above B.
+ const items = layout({
+ A: { at: 'L', via: null, depth: null, face: 'E' },
+ B: { at: null, via: 'A', depth: 2, parent: 'A', pside: 'N', face: 'S' },
+ C: { at: null, via: 'A', depth: 3, parent: 'B', pside: 'N', face: 'W' },
+ }, {});
+ assert.deepStrictEqual(cell(items, 'B'), [-1, -1]);
+ assert.deepStrictEqual(cell(items, 'C'), [-1, -2]);
+ assert.ok(!at(items, 'B')!.estimated && !at(items, 'C')!.estimated);
+ assert.strictEqual(at(items, 'B')!.rot, 0);
+ assert.strictEqual(at(items, 'C')!.rot, 3); // its W points down, back at B
+});
+
+test('a turned Keybit on top is placed by its chain, not by a guess', () => {
+ // Both report "left". K2 is really on top, turned (its E side points down).
+ // C hangs off K2's E side: with K2 on top that's the cell left of K2, the
+ // corner; with K2 on the left it would be the Keyword. Only one fits.
+ const items = layout({
+ K1: { at: 'L', via: null, depth: null, face: 'E' },
+ K2: { at: 'L', via: null, depth: null, face: 'E' },
+ C: { at: null, via: 'K2', depth: 2, parent: 'K2', pside: 'W', face: 'E' },
+ }, {});
+ assert.ok(!at(items, 'C')!.estimated);
+});
diff --git a/app/test/protocol.test.ts b/app/test/protocol.test.ts
index 4a88b2d..ff89649 100644
--- a/app/test/protocol.test.ts
+++ b/app/test/protocol.test.ts
@@ -125,3 +125,11 @@ test('OTA: stack reply, image checks and chunks', () => {
assert.deepStrictEqual(chunks.map((c) => c.length), [240, 240, 24]);
assert.deepStrictEqual([...chunks[2].slice(18)], [1, 1, 0xff, 0xff, 0xff, 0xff]);
});
+
+test('KEY+ with where a v11 Keybit is', () => {
+ assert.deepStrictEqual(parseLine('KEY+ uid=1560ABCD at=X via=FFFFFFFF7E8BBD5D1561ABCD depth=2 parent=1561ABCD pside=N face=S'), {
+ type: 'keyAdd', uid: '1560ABCD', at: null, v: null, via: 'FFFFFFFF7E8BBD5D1561ABCD', depth: 2,
+ face: 'S', parent: '1561ABCD', pside: 'N',
+ });
+ assert.strictEqual((parseLine('KEY+ uid=FFFFFFFF7E8BBD5D1561ABCD at=L v=11 face=E') as { face: string }).face, 'E');
+});