Skip to content

Commit

Permalink
fix(keybindings): add check function property and exclude checkbox fr…
Browse files Browse the repository at this point in the history
…om focus check
  • Loading branch information
micaelagoffe committed Nov 27, 2024
1 parent 15b35b7 commit d8daa32
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/keybindings/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export type KeyBinding = readonly [Matcher, Activity[], Info];
export type ActivityHandler = {
activity: Activity;
callback: () => void;
check?: () => boolean;
element?: () => Element | null | undefined;
};

Expand Down
21 changes: 15 additions & 6 deletions src/keybindings/use-keybindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const useKeybindings = (bindings: readonly KeyBinding[]): RegisterFn => {
const meta = useMeta<State>({ bindings });

useEffect(() => {
const handler = (e: KeyboardEvent) => {
const keyboardEventHandler = (e: KeyboardEvent) => {
if (e.defaultPrevented) {
return;
}
Expand All @@ -27,16 +27,25 @@ export const useKeybindings = (bindings: readonly KeyBinding[]): RegisterFn => {
if (handlers.length === 0) return;

// find first actionable handler
const handler = handlers.find(
(handler) => !handler.element || isInteractive(handler.element()),
);
const handler = handlers.find((handler) => {
if (
(handler.check && !handler.check()) ||
(handler.element && !isInteractive(handler.element()))
) {
return false;
}

return handler;
});

if (!handler) return;

e.preventDefault();
handler.callback();
};
document.addEventListener('keydown', handler, true);
return () => document.removeEventListener('keydown', handler, true);
document.addEventListener('keydown', keyboardEventHandler, true);
return () =>
document.removeEventListener('keydown', keyboardEventHandler, true);
}, []);

const register = useCallback((handler: ActivityHandler) => {
Expand Down
2 changes: 1 addition & 1 deletion src/keybindings/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const focusIsInEditableArea = (): boolean => {
const active = getActiveElement(document);

if (!active) return false;
if (active.matches('input, textarea')) return true;
if (active.matches('input:not([type="checkbox"]), textarea')) return true;
if ('isContentEditable' in active && active.isContentEditable) {
return true;
}
Expand Down

0 comments on commit d8daa32

Please sign in to comment.