@wordpress/block-editor
Version:
111 lines (84 loc) • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useFocusFirstElement = useFocusFirstElement;
var _lodash = require("lodash");
var _element = require("@wordpress/element");
var _dom = require("@wordpress/dom");
var _data = require("@wordpress/data");
var _dom2 = require("../../../utils/dom");
var _store = require("../../../store");
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/element').RefObject} RefObject */
/**
* Returns the initial position if the block needs to be focussed, `undefined`
* otherwise. The initial position is either 0 (start) or -1 (end).
*
* @param {string} clientId Block client ID.
*
* @return {number} The initial position, either 0 (start) or -1 (end).
*/
function useInitialPosition(clientId) {
return (0, _data.useSelect)(select => {
const {
getSelectedBlocksInitialCaretPosition,
isMultiSelecting,
isNavigationMode,
isBlockSelected
} = select(_store.store);
if (!isBlockSelected(clientId)) {
return;
}
if (isMultiSelecting() || isNavigationMode()) {
return;
} // If there's no initial position, return 0 to focus the start.
return getSelectedBlocksInitialCaretPosition();
}, [clientId]);
}
/**
* Transitions focus to the block or inner tabbable when the block becomes
* selected and an initial position is set.
*
* @param {string} clientId Block client ID.
*
* @return {RefObject} React ref with the block element.
*/
function useFocusFirstElement(clientId) {
const ref = (0, _element.useRef)();
const initialPosition = useInitialPosition(clientId);
(0, _element.useEffect)(() => {
if (initialPosition === undefined || initialPosition === null) {
return;
}
if (!ref.current) {
return;
}
const {
ownerDocument
} = ref.current; // Do not focus the block if it already contains the active element.
if (ref.current.contains(ownerDocument.activeElement)) {
return;
} // Find all tabbables within node.
const textInputs = _dom.focus.tabbable.find(ref.current).filter(node => (0, _dom.isTextField)(node)); // If reversed (e.g. merge via backspace), use the last in the set of
// tabbables.
const isReverse = -1 === initialPosition;
const target = (isReverse ? _lodash.last : _lodash.first)(textInputs) || ref.current;
if ( // Don't focus inner block or block appenders.
!(0, _dom2.isInsideRootBlock)(ref.current, target) || target.closest('.block-list-appender')) {
ref.current.focus();
return;
}
(0, _dom.placeCaretAtHorizontalEdge)(target, isReverse);
}, [initialPosition]);
return ref;
}
//# sourceMappingURL=use-focus-first-element.js.map