Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

15.6 KB
Raw Blame
/**
 * The resolved keymap and where the user's overrides live.
 *
 * Resolution = the registry's defaults for the current platform, overlaid by the stored
 * platform section's known ids (`null` = explicitly unbound). The stored document is the
 * account's `ui_prefs.keybindings`, mirrored to `localStorage["penguin.keybindings"]`: the
 * dispatcher installs at module evaluation, before auth and before any prefs request answers,
 * so the first keystroke needs a synchronous read, and the mirror's `storage` event is what
 * lets every other same-origin tab follow a change live. Only overrides are stored — a row set
 * back to its default is deleted from the section, so a later default change reaches users who
 * never touched that row — and ids the registry does not know are carried through untouched.
 *
 * Storage is injectable (the install-scope.ts convention: vitest runs in Node with no
 * localStorage), and every read degrades to the defaults on anything unexpected.
 */
import { chordEquals, normalizeChord, parseChord, serializeChord } from "./chord";
import { relocateChord } from "./match";
import { currentPlatform } from "./platform";
import { SHORTCUT_COMMANDS, commandById, defaultChord } from "./registry";
import type {
  Chord,
  CommandId,
  Keymap,
  Platform,
  ShortcutCommand,
  StoredKeybindings,
} from "./types";

/** The browser mirror of the account's overrides (a `browser`-scoped key in install-scope's KEY_RULES). */
export const KEYBINDINGS_KEY = "penguin.keybindings";

/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory one. */
export interface KeybindingsStorage {
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
  removeItem(key: string): void;
}

const SECTIONS: readonly Platform[] = ["mac", "windows", "linux"];

let storageOverride: KeybindingsStorage | null = null;
let layout: ReadonlyMap<string, string> | null = null;
let cache: { platform: Platform; keymap: Keymap } | null = null;
let version = 0;
const listeners = new Set<() => void>();
/** Whether this tab edited the bindings since it loaded: what decides an absent server copy's fate on hydrate. */
let writtenThisSession = false;
/** Where a write goes after the mirror: the account's prefs, installed once the session is signed in. */
let persister: ((doc: StoredKeybindings) => unknown) | null = null;

/**
 * Why the last write to the account's copy failed (`null` while the account holds every edit).
 *
 * The mirror is written first, so a refused write leaves each row showing the chord the edit just
 * made: the rows cannot say that the account never heard, and the next load hydrates the account's
 * copy over the mirror, which is exactly the change disappearing. So the store remembers the
 * failure — kept as the raw value, not a sentence, so a language switch re-words it — and the page
 * that holds the edits reads it (7.114). Its own version counter keeps `useSyncExternalStore`'s
 * snapshot memoization honest.
 */
let saveFailure: unknown = null;
let saveFailureVersion = 0;
const saveFailureListeners = new Set<() => void>();

function publishSaveFailure(next: unknown): void {
  saveFailure = next;
  saveFailureVersion++;
  for (const listener of [...saveFailureListeners]) listener();
}

/** Each attempt supersedes the last sentence: this edit may be the one that lands. */
function clearSaveFailure(): void {
  if (saveFailure !== null) publishSaveFailure(null);
}

function noteSaveFailure(error: unknown): void {
  publishSaveFailure(error);
}

/**
 * Why the account's copy was never read (`null` while it was).
 *
 * The dispatcher installs at module evaluation — before auth, before any prefs request answers — so
 * the keymap comes from the browser mirror until `GET /api/me/prefs` arrives. When that read is
 * refused the mirror simply stands, and it is the previous account's document or nothing at all;
 * worse, an edit then writes that document back **whole**, because one PUT replaces `keybindings`
 * instead of merging, so it can take away overrides the account held. No row can say any of this:
 * they read the mirror and look exactly like the account's copy. So the store keeps the raw failure
 * (not a sentence, so a language switch re-words it) for the page that holds the edits (7.115), and
 * drops it the moment the question is settled — a hydrate, or a write that lands (the account then
 * holds what is on screen).
 */
let loadFailure: unknown = null;
let loadFailureVersion = 0;
const loadFailureListeners = new Set<() => void>();

function publishLoadFailure(next: unknown): void {
  loadFailure = next;
  loadFailureVersion++;
  for (const listener of [...loadFailureListeners]) listener();
}

function clearLoadFailure(): void {
  if (loadFailure !== null) publishLoadFailure(null);
}

/** The prefs read the runtime asked for was refused: what the page shows is the mirror, not the account's copy. */
export function noteHydrateFailure(error: unknown): void {
  publishLoadFailure(error);
}

function storage(): KeybindingsStorage | null {
  if (storageOverride !== null) return storageOverride;
  try {
    return typeof localStorage === "undefined" ? null : localStorage;
  } catch {
    return null; // access denied (sandboxed frame, disabled storage)
  }
}

/**
 * The document shape, enforced: `v` must be 1 and only the three platform sections are kept,
 * each holding string-or-null values. Chord grammar is NOT checked here — an unparseable chord
 * is skipped at apply time and kept in the document, like an unknown id.
 */
export function sanitizeStored(value: unknown): StoredKeybindings {
  if (typeof value !== "object" || value === null || (value as { v?: unknown }).v !== 1) {
    return { v: 1 };
  }
  const out: StoredKeybindings = { v: 1 };
  for (const section of SECTIONS) {
    const raw = (value as Record<string, unknown>)[section];
    if (typeof raw !== "object" || raw === null || Array.isArray(raw)) continue;
    const entries: Record<string, string | null> = {};
    for (const [id, chord] of Object.entries(raw as Record<string, unknown>)) {
      if (chord === null || typeof chord === "string") entries[id] = chord;
    }
    out[section] = entries;
  }
  return out;
}

/** The stored document; malformed JSON, a foreign shape or a wrong `v` all read as "no overrides". */
export function readStored(store: KeybindingsStorage | null = storage()): StoredKeybindings {
  try {
    const raw = store?.getItem(KEYBINDINGS_KEY);
    if (raw === null || raw === undefined || raw === "") return { v: 1 };
    return sanitizeStored(JSON.parse(raw));
  } catch {
    return { v: 1 };
  }
}

/** The document without empty sections, which is the form both the mirror and the server hold. */
function compactDoc(doc: StoredKeybindings): StoredKeybindings {
  const compact: StoredKeybindings = { v: 1 };
  for (const section of SECTIONS) {
    const entries = doc[section];
    if (entries !== undefined && Object.keys(entries).length > 0) compact[section] = entries;
  }
  return compact;
}

function storeMirror(compact: StoredKeybindings): void {
  try {
    storage()?.setItem(KEYBINDINGS_KEY, JSON.stringify(compact));
  } catch {
    /* best-effort persistence (quota limits / private browsing) */
  }
}

/**
 * Hands the compact document to the account. A writer that answers with a promise is watched: a
 * rejection (or a synchronous throw) is remembered rather than swallowed, because nothing awaits
 * an edit — the mirror already carries it. A write that lands also settles the earlier question of
 * what the account held: from then on it holds this document.
 */
function sendToAccount(compact: StoredKeybindings): void {
  if (persister === null) return;
  try {
    const sent = persister(compact);
    if (sent instanceof Promise) void sent.then(clearLoadFailure, noteSaveFailure);
  } catch (error) {
    noteSaveFailure(error);
  }
}

/** A user edit: mirror first, so it applies at once here and in every other tab, then the account. */
function writeStored(doc: StoredKeybindings): void {
  const compact = compactDoc(doc);
  storeMirror(compact);
  writtenThisSession = true;
  clearSaveFailure();
  sendToAccount(compact);
  invalidate();
}

/**
 * Installs (or, with null, removes) the writer that carries an edit to the account's prefs. The
 * store stays free of the API client: the runtime that knows the session is signed in installs
 * it, and nothing is sent before then. Either call is an account boundary — sign-out is
 * client-side and reloads nothing — so the "edited this session" mark starts over here: an edit
 * made under the previous account must never be read as pending for the next one.
 */
export function setKeybindingsPersister(fn: ((doc: StoredKeybindings) => unknown) | null): void {
  persister = fn;
  writtenThisSession = false;
  // Another account's failed write is not this one's news.
  clearSaveFailure();
  // Nor is what the previous account's read said: this one's read is about to be asked for.
  clearLoadFailure();
}

/**
 * Reconciles the mirror with the account's copy once it arrives. The server wins: its document
 * replaces the mirror. An absent server copy means one of two things — this account edited the
 * bindings in this tab before the prefs answered, in which case the mirror is that edit and
 * stays (the persister already carried it, so nothing is sent again); or nothing was ever stored
 * for this account, in which case the mirror is cleared, so a browser that signs into another
 * account does not resurrect the previous account's bindings.
 */
export function hydrateFromServer(stored: unknown): void {
  // The screen is the account's copy again, so a sentence about a write it never got is stale.
  clearSaveFailure();
  // And the account's copy has now been read, so nothing is left to warn about.
  clearLoadFailure();
  if (stored !== undefined && stored !== null) {
    storeMirror(compactDoc(sanitizeStored(stored)));
    invalidate();
    return;
  }
  if (writtenThisSession) return;
  storage()?.removeItem(KEYBINDINGS_KEY);
  invalidate();
}

function invalidate(): void {
  cache = null;
  version++;
  for (const listener of [...listeners]) listener();
}

/** The registry default after the keyboard layout relocation, when a layout is known. */
function effectiveDefault(cmd: ShortcutCommand, platform: Platform): Chord | null {
  const chord = defaultChord(cmd, platform);
  return chord !== null && layout !== null ? relocateChord(chord, layout) : chord;
}

function resolve(platform: Platform): Keymap {
  const section = readStored()[platform] ?? {};
  const out = new Map<CommandId, Chord | null>();
  for (const cmd of SHORTCUT_COMMANDS) {
    const fallback = effectiveDefault(cmd, platform);
    if (!Object.hasOwn(section, cmd.id)) {
      out.set(cmd.id, fallback);
      continue;
    }
    const stored = section[cmd.id];
    if (stored === null || stored === undefined) {
      out.set(cmd.id, null);
      continue;
    }
    const parsed = parseChord(stored);
    out.set(cmd.id, parsed === null ? fallback : normalizeChord(parsed, platform));
  }
  return out;
}

/** The keymap for the current platform; cached until a write, a `storage` event or a layout arrives. */
export function keymap(): Keymap {
  const platform = currentPlatform();
  if (cache === null || cache.platform !== platform)
    cache = { platform, keymap: resolve(platform) };
  return cache.keymap;
}

export function bindingOf(id: CommandId): Chord | null {
  return keymap().get(id) ?? null;
}

/** True while the stored platform section carries an entry for the id (including an explicit unbind). */
export function isOverridden(id: CommandId): boolean {
  const section = readStored()[currentPlatform()];
  return section !== undefined && Object.hasOwn(section, id);
}

/** Binds (or, with null, unbinds) a command; a chord equal to the default removes the override instead. */
export function setBinding(id: CommandId, chord: Chord | null): void {
  const platform = currentPlatform();
  const doc = readStored();
  const section = { ...(doc[platform] ?? {}) };
  const normalized = chord === null ? null : normalizeChord(chord, platform);
  if (chordEquals(normalized, effectiveDefault(commandById(id), platform))) {
    delete section[id];
  } else {
    section[id] = normalized === null ? null : serializeChord(normalized);
  }
  writeStored({ ...doc, [platform]: section });
}

export function resetBinding(id: CommandId): void {
  const platform = currentPlatform();
  const doc = readStored();
  const section = { ...(doc[platform] ?? {}) };
  delete section[id];
  writeStored({ ...doc, [platform]: section });
}

/** Drops every override of the current platform; the other platforms' sections stay. */
export function resetAll(): void {
  const doc = readStored();
  delete doc[currentPlatform()];
  writeStored(doc);
}

/** The mirror changed underneath us (another tab's `storage` event, or a whole-store clear): re-read on the next access. */
export function noteExternalChange(key: string | null): void {
  if (key === null || key === KEYBINDINGS_KEY) invalidate();
}

/** `useSyncExternalStore` pair: subscribe, and a version that changes whenever the keymap may have. */
export function subscribeKeymap(listener: () => void): () => void {
  listeners.add(listener);
  return () => listeners.delete(listener);
}

export function keymapVersion(): number {
  return version;
}

/** The last refused write to the account's copy, as it arrived — `null` once one lands or a hydrate arrives. */
export function shortcutSaveFailure(): unknown {
  return saveFailure;
}

export function subscribeShortcutSaveFailure(listener: () => void): () => void {
  saveFailureListeners.add(listener);
  return () => saveFailureListeners.delete(listener);
}

export function shortcutSaveFailureVersion(): number {
  return saveFailureVersion;
}

/** Why the account's copy was never read, as it arrived — `null` once a read or a write settles it. */
export function shortcutLoadFailure(): unknown {
  return loadFailure;
}

export function subscribeShortcutLoadFailure(listener: () => void): () => void {
  loadFailureListeners.add(listener);
  return () => loadFailureListeners.delete(listener);
}

export function shortcutLoadFailureVersion(): number {
  return loadFailureVersion;
}

/**
 * The browser's `code → character` map, when it exposes one: defaults move to the key that types
 * their US character, and labels show the character a key actually types.
 */
export function applyKeyboardLayout(map: ReadonlyMap<string, string> | null): void {
  layout = map;
  invalidate();
}

export function keyboardLayout(): ReadonlyMap<string, string> | null {
  return layout;
}

/** Tests inject a storage and a layout; both null restores the browser defaults. */
export function configureKeybindingsStoreForTests(options: {
  storage?: KeybindingsStorage | null;
  layout?: ReadonlyMap<string, string> | null;
}): void {
  if (options.storage !== undefined) storageOverride = options.storage;
  if (options.layout !== undefined) layout = options.layout;
  writtenThisSession = false;
  persister = null;
  clearSaveFailure();
  clearLoadFailure();
  invalidate();
}

interface NavigatorKeyboard {
  keyboard?: {
    getLayoutMap?: () => Promise<{ forEach(cb: (value: string, key: string) => void): void }>;
  };
}

if (typeof window !== "undefined") {
  // Another tab wrote the mirror (the event never fires in the writing tab; writeStored notifies that one itself).
  window.addEventListener("storage", (event) => noteExternalChange(event.key));
  // Chromium and Electron expose the layout; Firefox and Safari do not and keep US positions.
  const keyboard = (navigator as NavigatorKeyboard).keyboard;
  keyboard
    ?.getLayoutMap?.()
    .then((map) => {
      const copy = new Map<string, string>();
      map.forEach((value, key) => copy.set(key, value));
      applyKeyboardLayout(copy);
    })
    .catch(() => {});
}