@wordpress/block-editor
Version:
71 lines (66 loc) • 2.01 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useFocusHandler = useFocusHandler;
var _data = require("@wordpress/data");
var _compose = require("@wordpress/compose");
var _dom = require("../../../utils/dom");
var _store = require("../../../store");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Selects the block if it receives focus.
*
* @param {string} clientId Block client ID.
*/
function useFocusHandler(clientId) {
const {
isBlockSelected
} = (0, _data.useSelect)(_store.store);
const {
selectBlock,
selectionChange
} = (0, _data.useDispatch)(_store.store);
return (0, _compose.useRefEffect)(node => {
/**
* Marks the block as selected when focused and not already
* selected. This specifically handles the case where block does not
* set focus on its own (via `setFocus`), typically if there is no
* focusable input in the block.
*
* @param {FocusEvent} event Focus event.
*/
function onFocus(event) {
// When the whole editor is editable, let writing flow handle
// selection.
if (node.parentElement.closest('[contenteditable="true"]')) {
return;
}
// Check synchronously because a non-selected block might be
// getting data through `useSelect` asynchronously.
if (isBlockSelected(clientId)) {
// Potentially change selection away from rich text.
if (!event.target.isContentEditable) {
selectionChange(clientId);
}
return;
}
// If an inner block is focussed, that block is responsible for
// setting the selected block.
if (!(0, _dom.isInsideRootBlock)(node, event.target)) {
return;
}
selectBlock(clientId);
}
node.addEventListener('focusin', onFocus);
return () => {
node.removeEventListener('focusin', onFocus);
};
}, [isBlockSelected, selectBlock]);
}
//# sourceMappingURL=use-focus-handler.js.map
;