useShortcutBindings.ts 1.6 KB

123456789101112131415161718192021222324252627282930
  1. /**
  2. * 快捷键内核的 React 桥接:生效表与展示 label 的唯一 hook 出口。
  3. *
  4. * 数据来源是 useSettings 的共享快照(setting.json),因此设置页写入 → update → refresh
  5. * 后所有消费方自动重算;不引入独立的 store/广播通道。
  6. */
  7. import { useMemo } from "react";
  8. import { type ShortcutCommandId } from "@zcode/shared";
  9. import { useSettings } from "@/hooks/useSettingService.js";
  10. import { resolveEffectiveShortcutBindings, type EffectiveShortcutBindings } from "./bindings.js";
  11. import { formatShortcutBindingLabel } from "./label.js";
  12. /** 当前生效的快捷键表(默认 + 用户覆盖合并后的只读视图)。 */
  13. export function useEffectiveShortcutBindings(): EffectiveShortcutBindings {
  14. const { settings } = useSettings();
  15. const overrides = settings?.shortcutBindings;
  16. return useMemo(() => resolveEffectiveShortcutBindings(overrides), [overrides]);
  17. }
  18. /**
  19. * 命令展示 label:生效表首个绑定格式化。
  20. * 未分配(覆盖为显式空数组)返回空串、不回退默认展示——tooltip 提示的键位必须与实际
  21. * 生效一致,否则清除后的命令仍提示默认键、按键却不响应(空数组语义的展示侧延伸)。
  22. * 生效表按命令表全集构建,只有非法 commandId 才会缺键,同样按无键处理。
  23. */
  24. export function useShortcutCommandLabel(commandId: ShortcutCommandId): string {
  25. const effective = useEffectiveShortcutBindings();
  26. const first = effective[commandId]?.[0] ?? "";
  27. return first === "" ? "" : formatShortcutBindingLabel(first);
  28. }