🚀 新規事業

keyboard-shortcuts

最終更新 2026年05月09日 / 40_新規事業/SCALE_Build/カタログ/機能集/keyboard-shortcuts.md

キーボードショートカット管理

用途

⌘+K, ?, Esc 等のキー操作を集中管理。フォーカス中の入力欄では無効化。

特徴

  • Cmd/Ctrl 修飾キー
  • シーケンス対応
  • INPUT 内では無効
  • チートシート自動生成

コード(コピペ用)

import { useEffect } from 'react';

type Shortcut = { keys: string; description: string; action: () => void };

export function useShortcuts(shortcuts: Shortcut[]) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      // フォーカス中の入力欄では無効
      const t = e.target as HTMLElement;
      if (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable) return;

      const key = e.key.toLowerCase();
      const mod = e.metaKey || e.ctrlKey;
      const shift = e.shiftKey;

      for (const s of shortcuts) {
        const parts = s.keys.toLowerCase().split('+');
        const wantMod = parts.includes('cmd') || parts.includes('ctrl');
        const wantShift = parts.includes('shift');
        const wantKey = parts.filter(p => !['cmd','ctrl','shift'].includes(p))[0];
        if (wantMod === mod && wantShift === shift && key === wantKey) {
          e.preventDefault();
          s.action();
          return;
        }
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [shortcuts]);
}

// 使い方:
// useShortcuts([
//   { keys: 'cmd+k', description: '検索を開く', action: openSearch },
//   { keys: 'cmd+shift+n', description: '新規作成', action: createNew },
//   { keys: '?', description: 'ヘルプ', action: showHelp },
// ]);

使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

注意事項

  • 依存パッケージを忘れず追加