UNPKG

@base-ui-components/react

Version:

Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.

40 lines (39 loc) 1.29 kB
import * as React from 'react'; import { ownerDocument } from '@base-ui-components/utils/owner'; import { EMPTY_OBJECT } from "./constants.js"; /** * Returns `click` and `mousedown` handlers that fix the behavior of triggers of popups that are toggled by different events. * For example, a button that opens a popup on mousedown and closes it on click. * This hook prevents the popup from closing immediately after the mouse button is released. */ export function useMixedToggleClickHandler(params) { const { enabled = true, mouseDownAction, open } = params; const ignoreClickRef = React.useRef(false); return React.useMemo(() => { if (!enabled) { return EMPTY_OBJECT; } return { onMouseDown: event => { if (mouseDownAction === 'open' && !open || mouseDownAction === 'close' && open) { ignoreClickRef.current = true; ownerDocument(event.currentTarget).addEventListener('click', () => { ignoreClickRef.current = false; }, { once: true }); } }, onClick: event => { if (ignoreClickRef.current) { ignoreClickRef.current = false; event.preventBaseUIHandler(); } } }; }, [enabled, mouseDownAction, open]); }