All files / src/hooks useKeyboardShortcuts.ts

0% Statements 0/258
100% Branches 0/0
0% Functions 0/1
0% Lines 0/258

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
'use client';

import { useEffect, useCallback, useRef } from 'react';

export interface KeyboardShortcut {
  /** The key to listen for (e.g., 's', 'Enter', 'Escape') */
  key: string;
  /** Require Ctrl/Cmd key */
  ctrl?: boolean;
  /** Require Shift key */
  shift?: boolean;
  /** Require Alt/Option key */
  alt?: boolean;
  /** Action to perform when shortcut is triggered */
  action: () => void;
  /** Description for help display */
  description: string;
  /** Category for grouping in help display */
  category?: string;
  /** Whether to prevent default browser behavior */
  preventDefault?: boolean;
  /** Whether to allow in input fields */
  allowInInput?: boolean;
}

interface UseKeyboardShortcutsOptions {
  /** Whether shortcuts are enabled (default: true) */
  enabled?: boolean;
  /** Scope identifier to prevent conflicts between components */
  scope?: string;
}

/**
 * Hook for registering keyboard shortcuts.
 *
 * Features:
 * - Modifier key support (Ctrl/Cmd, Shift, Alt)
 * - Automatic input field detection (skips shortcuts when typing)
 * - Configurable per-shortcut behavior
 * - Scoped shortcuts to prevent conflicts
 *
 * @example
 * ```tsx
 * useKeyboardShortcuts([
 *   {
 *     key: 's',
 *     ctrl: true,
 *     action: () => handleSave(),
 *     description: 'Save changes',
 *     category: 'Actions',
 *   },
 *   {
 *     key: 'Escape',
 *     action: () => handleClose(),
 *     description: 'Close modal',
 *   },
 * ]);
 * ```
 */
export function useKeyboardShortcuts(
  shortcuts: KeyboardShortcut[],
  options: UseKeyboardShortcutsOptions = {}
): KeyboardShortcut[] {
  const { enabled = true } = options;
  const shortcutsRef = useRef(shortcuts);

  // Update ref in an effect to avoid setting during render
  useEffect(() => {
    shortcutsRef.current = shortcuts;
  }, [shortcuts]);

  const handleKeyDown = useCallback(
    (event: KeyboardEvent) => {
      if (!enabled) return;

      const target = event.target as HTMLElement;
      const isInputField =
        target instanceof HTMLInputElement ||
        target instanceof HTMLTextAreaElement ||
        target instanceof HTMLSelectElement ||
        target.isContentEditable;

      for (const shortcut of shortcutsRef.current) {
        // Skip if in input field and not allowed
        if (isInputField && !shortcut.allowInInput) {
          continue;
        }

        // Check key match (case-insensitive for letters)
        const keyMatch =
          event.key.toLowerCase() === shortcut.key.toLowerCase() ||
          event.code.toLowerCase() === `key${shortcut.key.toLowerCase()}`;

        // Check modifier keys
        const ctrlMatch = shortcut.ctrl
          ? event.ctrlKey || event.metaKey
          : !event.ctrlKey && !event.metaKey;
        const shiftMatch = shortcut.shift ? event.shiftKey : !event.shiftKey;
        const altMatch = shortcut.alt ? event.altKey : !event.altKey;

        if (keyMatch && ctrlMatch && shiftMatch && altMatch) {
          if (shortcut.preventDefault !== false) {
            event.preventDefault();
          }
          shortcut.action();
          return;
        }
      }
    },
    [enabled]
  );

  useEffect(() => {
    if (!enabled) return;

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown, enabled]);

  return shortcuts;
}

/**
 * Format a shortcut for display (e.g., "Ctrl+S", "⌘+Shift+N")
 */
export function formatShortcut(shortcut: KeyboardShortcut): string {
  const isMac = typeof window !== 'undefined' && /Mac|iPod|iPhone|iPad/.test(navigator.platform);
  const parts: string[] = [];

  if (shortcut.ctrl) {
    parts.push(isMac ? '⌘' : 'Ctrl');
  }
  if (shortcut.alt) {
    parts.push(isMac ? '⌥' : 'Alt');
  }
  if (shortcut.shift) {
    parts.push('Shift');
  }

  // Format key name
  let keyName = shortcut.key;
  if (keyName === ' ') keyName = 'Space';
  if (keyName.length === 1) keyName = keyName.toUpperCase();

  parts.push(keyName);

  return parts.join('+');
}

/**
 * Get individual key parts for rendering
 */
export function getShortcutKeys(shortcut: KeyboardShortcut): string[] {
  const isMac = typeof window !== 'undefined' && /Mac|iPod|iPhone|iPad/.test(navigator.platform);
  const keys: string[] = [];

  if (shortcut.ctrl) {
    keys.push(isMac ? '⌘' : 'Ctrl');
  }
  if (shortcut.alt) {
    keys.push(isMac ? '⌥' : 'Alt');
  }
  if (shortcut.shift) {
    keys.push('Shift');
  }

  let keyName = shortcut.key;
  if (keyName === ' ') keyName = 'Space';
  if (keyName === 'Escape') keyName = 'Esc';
  if (keyName === 'ArrowUp') keyName = '↑';
  if (keyName === 'ArrowDown') keyName = '↓';
  if (keyName === 'ArrowLeft') keyName = '←';
  if (keyName === 'ArrowRight') keyName = '→';
  if (keyName === 'Enter') keyName = '↵';
  if (keyName.length === 1) keyName = keyName.toUpperCase();

  keys.push(keyName);

  return keys;
}

/**
 * Group shortcuts by category
 */
export function groupShortcutsByCategory(
  shortcuts: KeyboardShortcut[]
): Map<string, KeyboardShortcut[]> {
  const groups = new Map<string, KeyboardShortcut[]>();

  for (const shortcut of shortcuts) {
    const category = shortcut.category || 'General';
    const existing = groups.get(category) || [];
    existing.push(shortcut);
    groups.set(category, existing);
  }

  return groups;
}

/**
 * Default admin shortcuts configuration
 */
export const defaultAdminShortcuts: KeyboardShortcut[] = [
  {
    key: '?',
    action: () => {},
    description: 'Show keyboard shortcuts',
    category: 'General',
  },
  {
    key: 's',
    ctrl: true,
    action: () => {},
    description: 'Save current form',
    category: 'Actions',
    allowInInput: true,
  },
  {
    key: 'n',
    ctrl: true,
    action: () => {},
    description: 'Create new item',
    category: 'Actions',
  },
  {
    key: 'Escape',
    action: () => {},
    description: 'Close modal / Cancel',
    category: 'Actions',
  },
  {
    key: '/',
    action: () => {},
    description: 'Focus search',
    category: 'Search',
  },
  {
    key: 'd',
    alt: true,
    action: () => {},
    description: 'Go to Dashboard',
    category: 'Navigation',
  },
  {
    key: 'p',
    alt: true,
    action: () => {},
    description: 'Go to Products',
    category: 'Navigation',
  },
  {
    key: 'o',
    alt: true,
    action: () => {},
    description: 'Go to Orders',
    category: 'Navigation',
  },
];