Merge pull request #5118 from xyflow/refactor/use-key-press

Refactor/use key press
This commit is contained in:
Moritz Klack
2025-03-27 11:42:50 +01:00
committed by GitHub
2 changed files with 14 additions and 2 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@xyflow/system': patch
---
Do not swallow key events when a button is focused
+9 -2
View File
@@ -8,6 +8,7 @@ type KeyOrCode = 'key' | 'code';
export type UseKeyPressOptions = { export type UseKeyPressOptions = {
target?: Window | Document | HTMLElement | ShadowRoot | null; target?: Window | Document | HTMLElement | ShadowRoot | null;
actInsideInputWithModifier?: boolean; actInsideInputWithModifier?: boolean;
preventDefault?: boolean;
}; };
const defaultDoc = typeof document !== 'undefined' ? document : null; const defaultDoc = typeof document !== 'undefined' ? document : null;
@@ -88,7 +89,7 @@ export function useKeyPress(
if (keyCode !== null) { if (keyCode !== null) {
const downHandler = (event: KeyboardEvent) => { const downHandler = (event: KeyboardEvent) => {
modifierPressed.current = event.ctrlKey || event.metaKey || event.shiftKey; modifierPressed.current = event.ctrlKey || event.metaKey || event.shiftKey || event.altKey;
const preventAction = const preventAction =
(!modifierPressed.current || (modifierPressed.current && !options.actInsideInputWithModifier)) && (!modifierPressed.current || (modifierPressed.current && !options.actInsideInputWithModifier)) &&
isInputDOMNode(event); isInputDOMNode(event);
@@ -100,7 +101,13 @@ export function useKeyPress(
pressedKeys.current.add(event[keyOrCode]); pressedKeys.current.add(event[keyOrCode]);
if (isMatchingKey(keyCodes, pressedKeys.current, false)) { if (isMatchingKey(keyCodes, pressedKeys.current, false)) {
event.preventDefault(); const target = (event.composedPath?.()?.[0] || event.target) as Element | null;
const isInteractiveElement = target?.nodeName === 'BUTTON' || target?.nodeName === 'A';
if (options.preventDefault !== false && (modifierPressed.current || !isInteractiveElement)) {
event.preventDefault();
}
setKeyPressed(true); setKeyPressed(true);
} }
}; };