import { useEffect } from 'react';
import { useSyncedRef } from '../useSyncedRef/index.js';
import { off, on } from '../util/misc.js';
const DEFAULT_EVENTS = ['mousedown', 'touchstart'];
export function useClickOutside(ref, callback, events = DEFAULT_EVENTS) {
    const cbRef = useSyncedRef(callback);
    const refRef = useSyncedRef(ref);
    useEffect(() => {
        function handler(event) {
            if (!refRef.current.current)
                return;
            const { target: evtTarget } = event;
            const cb = cbRef.current;
            if (!evtTarget ||
                (Boolean(evtTarget) && !refRef.current.current.contains(evtTarget))) {
                cb.call(this, event);
            }
        }
        for (const name of events) {
            on(document, name, handler, { passive: true });
        }
        return () => {
            for (const name of events) {
                off(document, name, handler, { passive: true });
            }
        };
    }, [...events]);
}
