示例工程 21-keyboard-focus-a11y

21-keyboard-focus-a11y/demo-01-shortcut-match/keys.ts

typescript · 1.9 KB

type Binding = {
  id: string;
  combo: string;
  scope: "global" | "dialog" | "input";
};

type Context = "app" | "dialog" | "input";

const bindings: Binding[] = [
  { id: "search.focus", combo: "meta+k", scope: "global" },
  { id: "search.slash", combo: "/", scope: "global" },
  { id: "help.open", combo: "?", scope: "global" },
  { id: "help.close", combo: "escape", scope: "dialog" },
  { id: "help.confirm", combo: "meta+enter", scope: "dialog" },
  { id: "input.escape", combo: "escape", scope: "input" },
];

function normalize(key: string, modifiers: string[]): string {
  const order = ["meta", "ctrl", "alt", "shift"];
  const parts = order.filter((modifier) => modifiers.includes(modifier));
  const normalized = key === " " ? "space" : key.toLowerCase();
  return [...parts, normalized].join("+");
}

function match(combo: string, context: Context): string {
  return (
    bindings.find(
      (binding) =>
        binding.combo === combo &&
        (binding.scope === "global" || binding.scope === context),
    )?.id ?? "NONE"
  );
}

const normalized = [
  normalize("K", ["meta", "shift"]),
  normalize("K", ["shift", "meta"]),
  normalize(" ", []),
  normalize("Escape", []),
];

const matches = {
  appMetaK: match("meta+k", "app"),
  dialogEscape: match("escape", "dialog"),
  appEscape: match("escape", "app"),
  inputEscape: match("escape", "input"),
  appSlash: match("slash", "app"),
  unknown: match("meta+shift+k", "app"),
};

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      normalized[0] === "meta+shift+k" &&
      normalized[1] === "meta+shift+k" &&
      normalized[2] === "space" &&
      normalized[3] === "escape" &&
      matches.appMetaK === "search.focus" &&
      matches.dialogEscape === "help.close" &&
      matches.appEscape === "NONE" &&
      matches.inputEscape === "input.escape" &&
      matches.appSlash === "NONE" &&
      matches.unknown === "NONE",
    normalized,
    matches,
  }),
);