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.

42 lines (41 loc) 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useEnhancedClickHandler = useEnhancedClickHandler; var React = _interopRequireWildcard(require("react")); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * Provides a cross-browser way to determine the type of the pointer used to click. * Safari and Firefox do not provide the PointerEvent to the click handler (they use MouseEvent) yet. * Additionally, this implementation detects if the click was triggered by the keyboard. * * @param handler The function to be called when the button is clicked. The first parameter is the original event and the second parameter is the pointer type. */ function useEnhancedClickHandler(handler) { const lastClickInteractionTypeRef = React.useRef(''); const handlePointerDown = React.useCallback(event => { if (event.defaultPrevented) { return; } lastClickInteractionTypeRef.current = event.pointerType; }, []); const handleClick = React.useCallback(event => { // event.detail has the number of clicks performed on the element. 0 means it was triggered by the keyboard. if (event.detail === 0) { handler(event, 'keyboard'); return; } if ('pointerType' in event) { // Chrome and Edge correctly use PointerEvent handler(event, event.pointerType); } handler(event, lastClickInteractionTypeRef.current); lastClickInteractionTypeRef.current = ''; }, [handler]); return { onClick: handleClick, onPointerDown: handlePointerDown }; }