Skip to content

A truly modular keyboard

C

app: board on a grid with a square Keyword, sort out Keybits turned 90 degrees

Nathan0529b8caf815
diff --git a/app/src/renderer/src/components/Board.tsx b/app/src/renderer/src/components/Board.tsx
index 28bce7e..b947616 100644
--- a/app/src/renderer/src/components/Board.tsx
+++ b/app/src/renderer/src/components/Board.tsx
@@ -1,7 +1,9 @@
import clsx from 'clsx';
+import { ArrowLeftRight } from 'lucide-react';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { actionLabel, activeProfile, demo, entryOf, keyName, openAssign } from '../controller.ts';
-import { bounds, layout, type Placed } from '../lib/layout.ts';
+import { bounds, layout, otherSide, type Placed } from '../lib/layout.ts';
+import type { Side } from '../lib/types.ts';
import { useApp } from '../store.ts';
/** How long a Keybit that left keeps showing while it pops out, in ms. */
@@ -9,6 +11,12 @@ const LEAVE_MS = 200;
/** Tallest the board gets before it scales down, in px. */
const MAX_H = 320;
const PAD = 16;
+/** Where the user put Keybits that could be on the left or the top, by UID. */
+const PREFER_KEY = 'board-side';
+
+function loadPrefer(): Record<string, Side> {
+ try { return JSON.parse(localStorage.getItem(PREFER_KEY) || '{}'); } catch { return {}; }
+}
/**
* The Keyword from above: a slot on each side a Keybit can attach to, and
@@ -22,7 +30,15 @@ export function Board() {
useApp((s) => s.store); // labels follow the active profile
const isDemo = transport === 'demo';
- const placed = useMemo(() => layout(keys, sides), [keys, sides]);
+ const [prefer, setPrefer] = useState(loadPrefer);
+ const flip = (uid: string, now: Side) => {
+ const to = otherSide(now);
+ if (!to) return;
+ const next = { ...prefer, [uid]: to };
+ setPrefer(next);
+ try { localStorage.setItem(PREFER_KEY, JSON.stringify(next)); } catch { /* only a convenience */ }
+ };
+ const placed = useMemo(() => layout(keys, sides, prefer), [keys, sides, prefer]);
// Keep what just left on screen long enough to pop out.
const [leaving, setLeaving] = useState<Placed[]>([]);
@@ -57,9 +73,9 @@ export function Board() {
if (p.kind === 'keyword') {
return (
- <div key={p.id} style={style} className={clsx(move, 'flex flex-col items-center justify-center rounded-xl bg-keyword text-keyword-fg shadow-inner')}>
- <span className="font-semibold tracking-wide">Keyword</span>
- <small className="mt-0.5 text-[11px] opacity-70">{activeProfile().name}</small>
+ <div key={p.id} style={style} className={clsx(move, 'flex flex-col items-center justify-center overflow-hidden rounded-xl bg-keyword px-1.5 text-center text-keyword-fg shadow-inner')}>
+ <span className="text-sm font-semibold tracking-wide">Keyword</span>
+ <small className="mt-0.5 line-clamp-1 text-[11px] opacity-70">{activeProfile().name}</small>
</div>
);
}
@@ -96,6 +112,26 @@ export function Board() {
);
};
+ /** A Keybit that could be on the left or the top gets a button to swap it. */
+ const flipper = (p: Placed) => {
+ const k = p.uid ? keys[p.uid] : undefined;
+ if (p.kind !== 'keybit' || !p.side || !k?.at || !otherSide(k.at)) return null;
+ const to = otherSide(p.side) === 'T' ? 'top' : 'left';
+ return (
+ <button
+ key={`flip-${p.id}`}
+ type="button"
+ title={`Turned 90°? Move it to the ${to}`}
+ aria-label={`Move to the ${to}`}
+ onClick={() => flip(p.uid!, p.side!)}
+ style={{ left: p.x - b.x + p.w - 26, top: p.y - b.y + 4 }}
+ className="absolute grid size-[22px] place-items-center rounded-md text-muted hover:bg-line hover:text-fg motion-safe:transition-[left,top] motion-safe:duration-300"
+ >
+ <ArrowLeftRight size={13} />
+ </button>
+ );
+ };
+
return (
<div ref={box} className="flex flex-col items-center gap-2 rounded-xl border border-line bg-panel py-5">
<div
@@ -109,6 +145,7 @@ export function Board() {
>
{placed.map((p) => tile(p, false))}
{leaving.map((p) => tile(p, true))}
+ {placed.map(flipper)}
</div>
</div>
{isDemo && <p className="text-xs text-muted">Demo: click a side to attach or remove a Keybit.</p>}
diff --git a/app/src/renderer/src/lib/layout.ts b/app/src/renderer/src/lib/layout.ts
index 3ecb636..e897e93 100644
--- a/app/src/renderer/src/lib/layout.ts
+++ b/app/src/renderer/src/lib/layout.ts
@@ -1,13 +1,15 @@
// Where everything goes on the board view: the Keyword, its three side
-// slots, and every Keybit, touching it or chained behind one that is.
+// slots, and every Keybit, touching it or chained behind one that is. It all
+// sits on a grid of Keybit-sized cells, the Keyword being one cell too.
import type { Side } from './types.ts';
-/** Size of a Keybit tile and the gap between tiles, in unscaled px. */
+/** Size of a cell and the gap between cells, in unscaled px. */
export const TILE = 96;
export const GAP = 8;
const STEP = TILE + GAP;
-/** The Keyword itself is two tiles wide. */
-export const KEYWORD_W = 2 * TILE + GAP;
+
+/** The other side a Keybit reported on side s could be on, if any. */
+export const otherSide = (s: Side): Side | undefined => OTHER[s];
/** One thing to draw, with its top-left corner relative to the Keyword's. */
export interface Placed {
@@ -32,59 +34,91 @@ export interface LayoutKey {
depth: number | null;
}
-const SLOT_AT: Record<Side, [number, number]> = {
- T: [(KEYWORD_W - TILE) / 2, -STEP],
- L: [-STEP, 0],
- R: [KEYWORD_W + GAP, 0],
-};
-/** Away from the Keyword, and across, for a Keybit on each side. */
-const OUT: Record<Side, [number, number]> = { T: [0, -1], L: [-1, 0], R: [1, 0] };
+type Cell = [number, number];
+const SLOT: Record<Side, Cell> = { L: [-1, 0], T: [0, -1], R: [1, 0] };
+/** Straight out from the Keyword for a Keybit on each side. */
+const OUT: Record<Side, Cell> = { L: [-1, 0], T: [0, -1], R: [1, 0] };
+/**
+ * Where else a Keybit reported on a side could be. A Keybit turned 90
+ * degrees shows the Keyword the same side of itself on the top as one the
+ * usual way round shows it on the left, so the shared bus can't tell those
+ * two apart. Right is never mixed up.
+ */
+const OTHER: Partial<Record<Side, Side>> = { L: 'T', T: 'L' };
+const NEXT: Cell[] = [[0, -1], [-1, 0], [1, 0], [0, 1]];
+
+const key = ([x, y]: Cell) => `${x},${y}`;
/**
- * Lays out the board. A Keybit touching the Keyword goes in its side's slot.
- * A chained one is only known by the Keybit it was relayed through and how
- * many hops out it is, so until the firmware reports which side of its
- * parent it sits on, it's estimated: straight out from that Keybit, away
- * from the Keyword, one tile per hop, with Keybits at the same hop spread
- * across. One whose route is unknown goes in a row under the Keyword.
+ * 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(keys: Record<string, LayoutKey>, sides: Partial<Record<Side, boolean>>): Placed[] {
- const out: Placed[] = [{ id: 'keyword', kind: 'keyword', x: 0, y: 0, w: KEYWORD_W, h: TILE }];
- const bySide: Partial<Record<Side, string>> = {};
- for (const [uid, k] of Object.entries(keys)) if (k.at && !bySide[k.at]) bySide[k.at] = uid;
+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 cells = new Map<string, string>([[key([0, 0]), 'keyword']]);
+ const at: Record<string, Cell> = {};
+ const sideOf: Record<string, Side> = {};
- for (const side of ['L', 'T', 'R'] as Side[]) {
- const [x, y] = SLOT_AT[side];
- const uid = bySide[side];
- out.push(uid ? { id: uid, kind: 'keybit', x, y, w: TILE, h: TILE, side, uid }
- : { id: `slot-${side}`, kind: 'slot', x, y, w: TILE, h: TILE, side, present: !!sides[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;
+ sideOf[uid] = s;
+ at[uid] = SLOT[s];
}
+ // The Keyword's own side slots are only for Keybits touching it, and its
+ // bottom has the USB port.
+ for (const s of ['L', 'T', 'R'] as Side[]) cells.set(key(SLOT[s]), bySide[s] ?? `slot-${s}`);
+ cells.set(key([0, 1]), 'usb');
const chained = Object.entries(keys)
.filter(([, k]) => !k.at)
.sort(([a, ka], [b, kb]) => (ka.depth ?? 99) - (kb.depth ?? 99) || a.localeCompare(b));
- const used = new Map<string, number>();
- let loose = 0;
+ const hop: Record<string, Cell> = {}; // `${root uid}:${depth}` -> a cell at that hop
+ const loose: string[] = [];
for (const [uid, k] of chained) {
- const root = k.via ? keys[k.via] : undefined;
- if (!root?.at || !k.depth) {
- out.push({ id: uid, kind: 'keybit', uid, estimated: true, w: TILE, h: TILE, x: loose++ * STEP, y: STEP + GAP });
- continue;
- }
- const [ox, oy] = OUT[root.at];
- const [bx, by] = SLOT_AT[root.at];
- const hop = k.depth - 1;
- // Same parent and hop: 0, +1, -1, +2, ... tiles across.
- const key = `${k.via}:${hop}`;
- const n = used.get(key) ?? 0;
- used.set(key, n + 1);
- const across = n === 0 ? 0 : n % 2 ? (n + 1) / 2 : -n / 2;
- out.push({
- id: uid, kind: 'keybit', uid, estimated: true, w: TILE, h: TILE,
- x: bx + ox * STEP * hop + (oy ? across * STEP : 0),
- y: by + oy * STEP * hop + (ox ? across * STEP : 0),
- });
+ 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 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; }
+ const touching = (c: Cell) => NEXT.filter(([dx, dy]) => {
+ const who = cells.get(key([c[0] + dx, c[1] + dy]));
+ return who && who !== 'usb' && !who.startsWith('slot-');
+ }).length;
+ const straight = (c: Cell) => c[0] - from[0] === out[0] && c[1] - from[1] === out[1];
+ free.sort((a, b) => touching(b) - touching(a) || Number(straight(b)) - Number(straight(a)));
+ at[uid] = free[0];
+ cells.set(key(free[0]), uid);
+ hop[`${k.via}:${k.depth}`] ??= free[0];
+ }
+
+ 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]) }
+ // 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]) });
+ loose.forEach((uid, i) => out.push({ id: uid, kind: 'keybit', uid, estimated: true, ...px([i - 1, 2]) }));
return out;
}
diff --git a/app/test/layout.test.ts b/app/test/layout.test.ts
index d8ed3bb..6578109 100644
--- a/app/test/layout.test.ts
+++ b/app/test/layout.test.ts
@@ -1,14 +1,18 @@
import test from 'node:test';
import assert from 'node:assert';
-import { layout, bounds, TILE, GAP, KEYWORD_W } from '../src/renderer/src/lib/layout.ts';
+import { layout, bounds, TILE, GAP } from '../src/renderer/src/lib/layout.ts';
const STEP = TILE + GAP;
const at = (items: ReturnType<typeof layout>, id: string) => items.find((i) => i.id === id);
+const cell = (items: ReturnType<typeof layout>, id: string) => {
+ const p = at(items, id)!;
+ return [p.x / STEP, p.y / STEP];
+};
-test('empty board: the Keyword and three dashed slots', () => {
+test('empty board: the Keyword (one cell) and three dashed slots', () => {
const items = layout({}, {});
assert.deepStrictEqual(items.map((i) => i.kind), ['keyword', 'slot', 'slot', 'slot']);
- assert.deepStrictEqual(bounds(items), { x: -STEP, y: -STEP, w: KEYWORD_W + 2 * STEP, h: TILE + STEP });
+ assert.deepStrictEqual(bounds(items), { x: -STEP, y: -STEP, w: 2 * STEP + TILE, h: STEP + TILE });
});
test('chained Keybits go straight out from the one they came through', () => {
@@ -16,16 +20,38 @@ test('chained Keybits go straight out from the one they came through', () => {
TOP: { at: 'T', via: null, depth: null },
A: { at: null, via: 'TOP', depth: 2 },
B: { at: null, via: 'TOP', depth: 3 },
- C: { at: null, via: 'TOP', depth: 2 },
}, {});
- const top = at(items, 'TOP')!;
- assert.deepStrictEqual([at(items, 'A')!.x, at(items, 'A')!.y], [top.x, top.y - STEP]);
- assert.deepStrictEqual([at(items, 'B')!.x, at(items, 'B')!.y], [top.x, top.y - 2 * STEP]);
- assert.deepStrictEqual([at(items, 'C')!.x, at(items, 'C')!.y], [top.x + STEP, top.y - STEP]); // same hop: spread across
- assert.ok(at(items, 'A')!.estimated && !top.estimated);
+ assert.deepStrictEqual(cell(items, 'TOP'), [0, -1]);
+ assert.deepStrictEqual(cell(items, 'A'), [0, -2]);
+ assert.deepStrictEqual(cell(items, 'B'), [0, -3]);
+ assert.ok(at(items, 'A')!.estimated && !at(items, 'TOP')!.estimated);
});
-test('a chained Keybit with an unknown route still shows', () => {
- const items = layout({ X: { at: null, via: 'GONE', depth: 2 } }, {});
+test('two Keybits both reported on the left: the second goes on top, and a chained one closes the square', () => {
+ const items = layout({
+ K1: { at: 'L', via: null, depth: null },
+ K2: { at: 'L', via: null, depth: null },
+ C: { at: null, via: 'K2', depth: 2 },
+ }, {});
+ assert.deepStrictEqual(cell(items, 'K1'), [-1, 0]);
+ assert.deepStrictEqual(cell(items, 'K2'), [0, -1]);
+ assert.deepStrictEqual(cell(items, 'C'), [-1, -1]); // touches both, not straight up
+});
+
+test('the side the user picked wins', () => {
+ const items = layout({ K1: { at: 'L', via: null, depth: null }, K2: { at: 'L', via: null, depth: null } }, {}, { K2: 'L' });
+ assert.deepStrictEqual(cell(items, 'K2'), [-1, 0]);
+ assert.deepStrictEqual(cell(items, 'K1'), [0, -1]);
+});
+
+test('chained Keybits never share a cell, and an unknown route still shows', () => {
+ const items = layout({
+ R: { at: 'R', via: null, depth: null },
+ A: { at: null, via: 'R', depth: 2 },
+ B: { at: null, via: 'R', depth: 2 },
+ X: { at: null, via: 'GONE', depth: 2 },
+ }, {});
+ const cells = items.map((i) => `${i.x},${i.y}`);
+ assert.strictEqual(new Set(cells).size, cells.length);
assert.ok(at(items, 'X'));
});