@gechiui/compose
Version:
GeChiUI higher-order components (HOCs).
60 lines (53 loc) • 1.68 kB
JavaScript
/**
* GeChiUI dependencies
*/
import { useRef, useEffect, useCallback } from '@gechiui/element';
import { focus } from '@gechiui/dom';
/**
* Hook used to focus the first tabbable element on mount.
*
* @param {boolean | 'firstElement'} focusOnMount Focus on mount mode.
* @return {import('react').RefCallback<HTMLElement>} Ref callback.
*
* @example
* ```js
* import { useFocusOnMount } from '@gechiui/compose';
*
* const WithFocusOnMount = () => {
* const ref = useFocusOnMount()
* return (
* <div ref={ ref }>
* <Button />
* <Button />
* </div>
* );
* }
* ```
*/
export default function useFocusOnMount() {
let focusOnMount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'firstElement';
const focusOnMountRef = useRef(focusOnMount);
useEffect(() => {
focusOnMountRef.current = focusOnMount;
}, [focusOnMount]);
return useCallback(node => {
var _node$ownerDocument$a, _node$ownerDocument;
if (!node || focusOnMountRef.current === false) {
return;
}
if (node.contains((_node$ownerDocument$a = (_node$ownerDocument = node.ownerDocument) === null || _node$ownerDocument === void 0 ? void 0 : _node$ownerDocument.activeElement) !== null && _node$ownerDocument$a !== void 0 ? _node$ownerDocument$a : null)) {
return;
}
let target = node;
if (focusOnMountRef.current === 'firstElement') {
const firstTabbable = focus.tabbable.find(node)[0];
if (firstTabbable) {
target =
/** @type {HTMLElement} */
firstTabbable;
}
}
target.focus();
}, []);
}
//# sourceMappingURL=index.js.map