All files / src/pages/flowsheet-page/flowsheet GlobalShortcutInputBlocker.tsx

91.66% Statements 11/12
92.3% Branches 12/13
100% Functions 6/6
100% Lines 10/10

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          1714x       173x 173x 173x               157x                       173x 11x       36x 36x     1714x    
import { useEffect } from "react";
 
// Prevents global keyboard shortcuts from triggering when typing in text inputs
// To allow more keys (e.g., arrow keys) to work while typing, add them to isAllowedKey
export function GlobalShortcutInputBlocker() {
  useEffect(() => {
    // Returns true if the event target is a text input, textarea, or content-editable element
    // This determines if the user is currently typing in an input field
    function isTextInput(target: EventTarget | null): boolean {
      Iif (!(target instanceof HTMLElement)) return false;
      const tag = target.tagName;
      return tag === "INPUT" || tag === "TEXTAREA" || target.isContentEditable;
    }
 
    // This method determines which keys are allowed to propagate while typing in a text input
    // Only Escape and Enter are allowed for now
    // All other keys will block global shortcuts
    // If you want to allow more keys (eg. arrow keys) add them here
    function isAllowedKey(key: string) {
      return (
        key === "Escape" ||
        key === "Enter" ||
        key === "ArrowUp" ||
        key === "ArrowDown" ||
        key === "ArrowLeft" ||
        key === "ArrowRight"
      );
    }
 
    function handler(event: KeyboardEvent) {
      // allow escape and enter keys even in text input
      if (isTextInput(event.target) && !isAllowedKey(event.key)) {
        event.stopPropagation();
      }
    }
 
    window.addEventListener("keydown", handler, true); // use capture phase
    return () => window.removeEventListener("keydown", handler, true);
  }, []);
 
  return null;
}