import { useMemo } from 'react';
import { useEventListener } from '../useEventListener/index.js';
import { useSyncedRef } from '../useSyncedRef/index.js';
import { isBrowser } from '../util/const.js';
import { yieldFalse, yieldTrue } from '../util/misc.js';
const createKeyPredicate = (keyFilter) => {
    if (typeof keyFilter === 'function')
        return keyFilter;
    if (typeof keyFilter === 'string')
        return (ev) => ev.key === keyFilter;
    return keyFilter ? yieldTrue : yieldFalse;
};
const WINDOW_OR_NULL = isBrowser ? window : null;
export function useKeyboardEvent(keyOrPredicate, callback, deps = [], options = {}) {
    const { event = 'keydown', target = WINDOW_OR_NULL, eventOptions } = options;
    const cbRef = useSyncedRef(callback);
    const handler = useMemo(() => {
        const predicate = createKeyPredicate(keyOrPredicate);
        return function (ev) {
            if (predicate(ev)) {
                cbRef.current.call(this, ev);
            }
        };
    }, deps);
    useEventListener(target, event, handler, eventOptions);
}
