Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

8.0 KB
Raw Blame
import { useMemo } from "react";
import { codeToKeyToken, codeToModifierToken } from "@/hooks/useHotkey";
import { useT } from "@/i18n";
import {
  ARROW_ROWS,
  MOUSE_CAPS,
  NAV_ROWS,
  mainRows,
  type KeyCap,
  type KeyboardPlatform,
  type KeyRow,
} from "./keyboardLayout";

/** The bindable jarvis token for a cap, or null when it cannot be bound. */
function capToken(cap: KeyCap, platform: KeyboardPlatform): string | null {
  if (cap.dead) return null;
  if (cap.token) return cap.token;
  return codeToModifierToken(cap.code, platform) ?? codeToKeyToken(cap.code);
}

interface KeyboardMapProps {
  /** Physical ``event.code``s currently held — drives the LIVE highlight. */
  pressedCodes: Set<string>;
  /** Tokens that make up the combo being built — drives the selected ring. */
  selectedTokens: Set<string>;
  /** token → label of ANOTHER action already bound to it (the "used" marker). */
  boundTokens: Record<string, string>;
  platform: KeyboardPlatform;
  /** Toggle a bindable key in/out of the combo (click-to-assign). */
  onToggleToken: (token: string) => void;
  /**
   * Whether this host can bind a mouse button. False hides the cluster rather
   * than offering a control that cannot work (Wayland, a Mac without pyobjc);
   * ``mouseReason`` is the backend's English sentence saying why.
   */
  mouseSupported?: boolean;
  mouseReason?: string;
}

function Key({
  cap,
  platform,
  pressedCodes,
  selectedTokens,
  boundTokens,
  onToggleToken,
}: {
  cap: KeyCap;
  platform: KeyboardPlatform;
  pressedCodes: Set<string>;
  selectedTokens: Set<string>;
  boundTokens: Record<string, string>;
  onToggleToken: (token: string) => void;
}) {
  const token = capToken(cap, platform);
  // Every key the backend can register is clickable — including the Meta key.
  // It used to be drawn dead with a "reserved by the system" tooltip, on the
  // premise that the OS claims it. That was wrong for this app: the Windows
  // backend polls the key state instead of registering with the shell, so it
  // sees Win combos like any other. Click-to-assign matters MOST for this key,
  // because pressing it physically makes Windows open Start and pull focus out
  // of the app mid-recording.
  const bindable = token !== null;
  const pressed = pressedCodes.has(cap.code);
  const selected = bindable && selectedTokens.has(token);
  const boundLabel = bindable ? boundTokens[token] : undefined;

  // Visual precedence: a live press always wins (you must SEE the key you hit),
  // then the in-combo selection, then the "used by another action" marker.
  const cls = pressed
    ? "border-border-strong bg-primary text-primary-foreground"
    : selected
      ? "bg-secondary text-foreground-strong"
      : boundLabel
        ? "bg-secondary text-foreground"
        : bindable
          ? // Hover stays clearly weaker than the "pressed" fill — a full
            // bg-accent hover read as "this key is pressed" in live testing.
            "border-input bg-background text-foreground hover:border-border-strong hover:bg-secondary"
          : "border-transparent bg-muted text-muted-foreground";

  return (
    <button
      type="button"
      data-testid={`key-${cap.code}`}
      aria-label={cap.code}
      aria-pressed={selected}
      title={boundLabel ? `${cap.label} — ${boundLabel}` : cap.label}
      disabled={!bindable}
      onClick={bindable ? () => onToggleToken(token) : undefined}
      style={{ flexGrow: cap.width ?? 1, flexBasis: 0 }}
      className={`relative flex h-7 min-w-0 items-center justify-center rounded border px-0.5 font-mono text-micro transition-colors ${cls} ${
        bindable ? "cursor-pointer" : "cursor-default"
      }`}
    >
      <span className="truncate">{cap.label}</span>
      {boundLabel && !pressed && (
        <span className="absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full bg-foreground" />
      )}
    </button>
  );
}

type KeyProps = Pick<
  KeyboardMapProps,
  "pressedCodes" | "selectedTokens" | "boundTokens" | "platform" | "onToggleToken"
>;

function Row({ row, ...rest }: { row: KeyRow } & KeyProps) {
  return (
    <div className="flex gap-1">
      {row.map((cap) => (
        <Key key={cap.code} cap={cap} {...rest} />
      ))}
    </div>
  );
}

/**
 * A live on-screen keyboard for the keybind picker. Keys light up as the user
 * presses them (so you can SEE that F5+F6 actually registered), keys already
 * bound to another action are flagged so you can pick a free one, and clicking a
 * key toggles it into the combo (click-to-assign — for keys that are awkward to
 * hold). Platform-aware modifier labels (⌘/⌥/⌃ on Mac, Ctrl/Win/Alt on PC).
 */
export function KeyboardMap({
  pressedCodes,
  selectedTokens,
  boundTokens,
  platform,
  onToggleToken,
  mouseSupported = true,
  mouseReason,
}: KeyboardMapProps) {
  const t = useT();
  const keyProps: KeyProps = {
    pressedCodes,
    selectedTokens,
    boundTokens,
    platform,
    onToggleToken,
  };
  const rows = useMemo(() => mainRows(platform), [platform]);

  return (
    <div className="mt-3 rounded-md border border-border bg-background p-2">
      <div className="flex flex-wrap items-start gap-3">
        {/* Main alpha block */}
        <div className="flex min-w-[280px] flex-1 flex-col gap-1">
          {rows.map((row, i) => (
            <Row key={i} row={row} {...keyProps} />
          ))}
        </div>

        {/* Nav cluster + inverted-T arrows */}
        <div className="flex flex-col gap-2">
          <div className="flex flex-col gap-1">
            {NAV_ROWS.map((row, i) => (
              <div key={i} className="flex gap-1">
                {row.map((cap) => (
                  <div key={cap.code} className="w-10">
                    <Key cap={cap} {...keyProps} />
                  </div>
                ))}
              </div>
            ))}
          </div>
          <div className="flex flex-col gap-1">
            {ARROW_ROWS.map((row, i) => (
              <div key={i} className="flex gap-1">
                {row.map((cap, j) =>
                  cap ? (
                    <div key={cap.code} className="w-10">
                      <Key cap={cap} {...keyProps} />
                    </div>
                  ) : (
                    <div key={`pad-${j}`} className="w-10" />
                  ),
                )}
              </div>
            ))}
          </div>

          {/* Mouse buttons. Click-to-assign is the reliable path here: a side
              button is Back/Forward in most apps and the middle button starts
              autoscroll, so the physical press may be consumed before the
              recorder sees it. */}
          {mouseSupported ? (
            <div className="flex gap-1">
              {MOUSE_CAPS.map((cap) => (
                <div key={cap.code} className="w-[3.25rem]">
                  <Key cap={cap.labelKey ? { ...cap, label: t(cap.labelKey) } : cap} {...keyProps} />
                </div>
              ))}
            </div>
          ) : (
            mouseReason && (
              <p
                data-testid="mouse-unavailable"
                className="max-w-[10rem] text-micro text-muted-foreground"
              >
                {mouseReason}
              </p>
            )
          )}
        </div>
      </div>

      {/* Legend */}
      <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-micro text-muted-foreground">
        <span className="flex items-center gap-1">
          <span className="inline-block h-2.5 w-2.5 rounded-sm bg-secondary" />
          {t("settings_view.keybinds.keyboard.legend_pressed")}
        </span>
        <span className="flex items-center gap-1">
          <span className="inline-block h-2.5 w-2.5 rounded-sm bg-secondary" />
          {t("settings_view.keybinds.keyboard.legend_selected")}
        </span>
        <span className="flex items-center gap-1">
          <span className="inline-block h-2.5 w-2.5 rounded-full bg-foreground" />
          {t("settings_view.keybinds.keyboard.legend_bound")}
        </span>
        <span className="ml-auto">
          {t("settings_view.keybinds.keyboard.hint")}
        </span>
      </div>
    </div>
  );
}