Skip to content

A truly modular keyboard

C

app: draw chained Keybits on the board, fit it to the panel, animate Keybits in and out

Nathand8dee17ae8e0
diff --git a/app/src/renderer/src/components/Board.tsx b/app/src/renderer/src/components/Board.tsx
index 1bbad3f..28bce7e 100644
--- a/app/src/renderer/src/components/Board.tsx
+++ b/app/src/renderer/src/components/Board.tsx
@@ -1,9 +1,20 @@
import clsx from 'clsx';
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { actionLabel, activeProfile, demo, entryOf, keyName, openAssign } from '../controller.ts';
-import type { Side } from '../lib/types.ts';
+import { bounds, layout, type Placed } from '../lib/layout.ts';
import { useApp } from '../store.ts';
-/** The Keyword from above, with a slot on each side a Keybit can attach to. */
+/** How long a Keybit that left keeps showing while it pops out, in ms. */
+const LEAVE_MS = 200;
+/** Tallest the board gets before it scales down, in px. */
+const MAX_H = 320;
+const PAD = 16;
+
+/**
+ * The Keyword from above: a slot on each side a Keybit can attach to, and
+ * every Keybit chained further out. It scales down to fit as the board
+ * grows; Keybits pop in and out and the rest slide to their new places.
+ */
export function Board() {
const keys = useApp((s) => s.keys);
const sides = useApp((s) => s.sides);
@@ -11,26 +22,73 @@ export function Board() {
useApp((s) => s.store); // labels follow the active profile
const isDemo = transport === 'demo';
- const slot = (side: Side, className: string) => {
- const uid = Object.entries(keys).find(([, k]) => k.at === side)?.[0];
- const present = !!uid || !!sides[side];
+ const placed = useMemo(() => layout(keys, sides), [keys, sides]);
+
+ // Keep what just left on screen long enough to pop out.
+ const [leaving, setLeaving] = useState<Placed[]>([]);
+ const last = useRef<Placed[]>(placed);
+ useEffect(() => {
+ const now = new Set(placed.map((p) => p.id));
+ const gone = last.current.filter((p) => p.kind === 'keybit' && !now.has(p.id));
+ last.current = placed;
+ if (!gone.length) return;
+ setLeaving((l) => [...l.filter((p) => !now.has(p.id)), ...gone]);
+ // Not cleared when placed changes again: several Keybits often leave in a row.
+ setTimeout(() => setLeaving((l) => l.filter((p) => !gone.includes(p))), LEAVE_MS);
+ }, [placed]);
+
+ // Fit everything in the panel's width and MAX_H.
+ const box = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(0);
+ useLayoutEffect(() => {
+ const el = box.current;
+ if (!el) return;
+ const ro = new ResizeObserver(() => setWidth(el.clientWidth));
+ ro.observe(el);
+ setWidth(el.clientWidth);
+ return () => ro.disconnect();
+ }, []);
+ const b = bounds([...placed, ...leaving]);
+ const scale = width ? Math.min(1, (width - 2 * PAD) / b.w, MAX_H / b.h) : 1;
+
+ const tile = (p: Placed, gone: boolean) => {
+ const style = { left: p.x - b.x, top: p.y - b.y, width: p.w, height: p.h };
+ const move = 'absolute motion-safe:transition-[left,top] motion-safe:duration-300 motion-safe:ease-out';
+
+ 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>
+ );
+ }
+
+ const uid = p.uid;
+ const present = !!uid || !!p.present;
const label = !present ? '' : uid ? actionLabel(entryOf(uid)) || keyName(uid) : 'Keybit';
return (
<button
+ key={p.id}
type="button"
- title={uid ? `${keyName(uid)} · uid ${uid}` : isDemo ? 'Attach a Keybit here' : ''}
- disabled={!isDemo && !uid}
+ style={style}
+ title={uid ? `${keyName(uid)} · uid ${uid}${p.estimated ? ' · position estimated' : ''}` : isDemo ? 'Attach a Keybit here' : ''}
+ disabled={gone || (!isDemo && !uid) || (isDemo && !p.side)}
onClick={() => {
const d = demo();
- if (d) d.toggle(side);
+ if (d && p.side) d.toggle(p.side);
else if (uid) openAssign(uid);
}}
className={clsx(
- 'grid place-items-center overflow-hidden rounded-xl border-2 px-1.5 text-center text-xs font-medium transition-all',
- present ? 'border-solid border-on bg-on-soft text-on' : 'border-dashed border-line text-transparent',
- uid && keys[uid].pressed && 'scale-95 border-accent bg-press text-accent',
- (isDemo || uid) && 'hover:border-accent',
- className,
+ move,
+ 'grid place-items-center overflow-hidden rounded-xl border-2 px-1.5 text-center text-xs font-medium',
+ !present ? 'border-dashed border-line text-transparent'
+ : p.estimated ? 'border-dashed border-on bg-on-soft/70 text-on' /* placed by a guess */
+ : 'border-solid border-on bg-on-soft text-on',
+ uid && keys[uid]?.pressed && 'scale-95 border-accent bg-press text-accent',
+ (isDemo || uid) && !gone && 'hover:border-accent',
+ p.kind === 'keybit' && (gone ? 'motion-safe:animate-tile-out' : 'motion-safe:animate-tile-in'),
+ gone && 'pointer-events-none opacity-0',
)}
>
<span className="line-clamp-2">{label}</span>
@@ -39,15 +97,19 @@ export function Board() {
};
return (
- <div className="flex flex-col items-center gap-2 rounded-xl border border-line bg-panel py-5">
- <div className="grid grid-cols-[96px_200px_96px] grid-rows-[96px_96px] gap-2" aria-label="The Keyword and its sides">
- {slot('T', 'col-start-2 row-start-1 mx-auto w-24')}
- {slot('L', 'col-start-1 row-start-2')}
- <div className="col-start-2 row-start-2 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 ref={box} className="flex flex-col items-center gap-2 rounded-xl border border-line bg-panel py-5">
+ <div
+ className="relative motion-safe:transition-[width,height] motion-safe:duration-300"
+ style={{ width: b.w * scale, height: b.h * scale }}
+ >
+ <div
+ className="absolute top-0 left-0 origin-top-left motion-safe:transition-transform motion-safe:duration-300 motion-safe:ease-out"
+ style={{ width: b.w, height: b.h, transform: `scale(${scale})` }}
+ aria-label="The Keyword and the Keybits on it"
+ >
+ {placed.map((p) => tile(p, false))}
+ {leaving.map((p) => tile(p, true))}
</div>
- {slot('R', 'col-start-3 row-start-2')}
</div>
{isDemo && <p className="text-xs text-muted">Demo: click a side to attach or remove a Keybit.</p>}
</div>
diff --git a/app/src/renderer/src/index.css b/app/src/renderer/src/index.css
index 8480c14..ec0af8b 100644
--- a/app/src/renderer/src/index.css
+++ b/app/src/renderer/src/index.css
@@ -62,6 +62,8 @@
--font-mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
--animate-pop: pop 1.4s ease-out;
--animate-blink: blink 0.5s ease-out;
+ --animate-tile-in: tile-in 0.25s ease-out;
+ --animate-tile-out: tile-out 0.2s ease-in forwards;
@keyframes pop {
0% { box-shadow: 0 0 0 3px var(--on); }
@@ -71,6 +73,14 @@
0% { color: var(--accent); }
100% { color: inherit; }
}
+ @keyframes tile-in {
+ 0% { opacity: 0; transform: scale(0.6); }
+ 100% { opacity: 1; transform: scale(1); }
+ }
+ @keyframes tile-out {
+ 0% { opacity: 1; transform: scale(1); }
+ 100% { opacity: 0; transform: scale(0.6); }
+ }
}
@layer base {
diff --git a/app/src/renderer/src/lib/layout.ts b/app/src/renderer/src/lib/layout.ts
new file mode 100644
index 0000000..3ecb636
--- /dev/null
+++ b/app/src/renderer/src/lib/layout.ts
@@ -0,0 +1,96 @@
+// Where everything goes on the board view: the Keyword, its three side
+// slots, and every Keybit, touching it or chained behind one that is.
+import type { Side } from './types.ts';
+
+/** Size of a Keybit tile and the gap between tiles, 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;
+
+/** One thing to draw, with its top-left corner relative to the Keyword's. */
+export interface Placed {
+ id: string;
+ kind: 'keyword' | 'slot' | 'keybit';
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ side?: Side;
+ uid?: string;
+ /** A slot the Keyword reports something on, before its Keybit is known. */
+ present?: boolean;
+ /** Placed by a guess (chained Keybits until the firmware says where they are). */
+ estimated?: boolean;
+}
+
+/** What layout() needs to know about a Keybit. */
+export interface LayoutKey {
+ at: Side | null;
+ via: string | null;
+ 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] };
+
+/**
+ * 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.
+ */
+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;
+
+ 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 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;
+ 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),
+ });
+ }
+ return out;
+}
+
+/** The smallest box around everything placed. */
+export function bounds(items: Placed[]) {
+ const x = Math.min(...items.map((i) => i.x));
+ const y = Math.min(...items.map((i) => i.y));
+ return { x, y, w: Math.max(...items.map((i) => i.x + i.w)) - x, h: Math.max(...items.map((i) => i.y + i.h)) - y };
+}
diff --git a/app/src/renderer/src/lib/transports.ts b/app/src/renderer/src/lib/transports.ts
index 8531bbe..60bc00d 100644
--- a/app/src/renderer/src/lib/transports.ts
+++ b/app/src/renderer/src/lib/transports.ts
@@ -144,8 +144,9 @@ export class DemoTransport implements Transport {
readonly label = 'Demo';
readonly kind = 'demo';
readonly uids: Record<Side, string> = { L: '3B0A4F1C88D2E61F5F1821C1', R: '91C7002DE4B3A75C0A33B7E2', T: '0F5E19A2C6B84D37C4D90015' };
- /** A Keybit chained behind the right one, reported by its low 32 bits like a real relay. */
+ /** Two Keybits chained out from the right one (2 and 3 hops), reported by their low 32 bits like a real relay. */
readonly chained = 'D00DF00D';
+ readonly chained2 = 'C0FFEE42';
private versions: Record<Side, number> = { L: 3, R: 2, T: 3 };
readonly present: Record<Side, boolean> = { L: true, R: false, T: false };
private maps: Record<string, Record<string, string>> = {};
@@ -169,18 +170,20 @@ export class DemoTransport implements Transport {
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 chainedLine() { return `KEY+ uid=${this.chained} at=X via=${this.uids.R} depth=1 v=3`; }
+ 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`;
+ }
/** Attaches or removes the Keybit on a side. */
toggle(side: Side) {
this.present[side] = !this.present[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}`);
+ if (side === 'R') this.emit(this.present.R ? this.chainedLine() : `KEY- uid=${this.chained}\nKEY- uid=${this.chained2}`);
this.emit(this.sidesLine());
}
private sideOf(uid: string): Side | 'X' | undefined {
- return SIDES.find((s) => this.uids[s] === uid && this.present[s]) || (uid === this.chained && this.present.R ? 'X' : undefined);
+ return SIDES.find((s) => this.uids[s] === uid && this.present[s]) || ((uid === this.chained || uid === this.chained2) && this.present.R ? 'X' : undefined);
}
/** Simulates a press and release. */
diff --git a/app/test/layout.test.ts b/app/test/layout.test.ts
new file mode 100644
index 0000000..d8ed3bb
--- /dev/null
+++ b/app/test/layout.test.ts
@@ -0,0 +1,31 @@
+import test from 'node:test';
+import assert from 'node:assert';
+import { layout, bounds, TILE, GAP, KEYWORD_W } 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);
+
+test('empty board: the Keyword 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 });
+});
+
+test('chained Keybits go straight out from the one they came through', () => {
+ const items = layout({
+ 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);
+});
+
+test('a chained Keybit with an unknown route still shows', () => {
+ const items = layout({ X: { at: null, via: 'GONE', depth: 2 } }, {});
+ assert.ok(at(items, 'X'));
+});