@wordpress/editor
Version:
Enhanced block editor for WordPress posts.
71 lines (67 loc) • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = usePostTitleFocus;
var _element = require("@wordpress/element");
var _data = require("@wordpress/data");
var _store = require("../../store");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Custom hook that manages the focus behavior of the post title input field.
*
* @param {Element} forwardedRef - The forwarded ref for the input field.
*
* @return {Object} - The ref object.
*/
function usePostTitleFocus(forwardedRef) {
const ref = (0, _element.useRef)();
const {
isCleanNewPost
} = (0, _data.useSelect)(select => {
const {
isCleanNewPost: _isCleanNewPost
} = select(_store.store);
return {
isCleanNewPost: _isCleanNewPost()
};
}, []);
(0, _element.useImperativeHandle)(forwardedRef, () => ({
focus: () => {
ref?.current?.focus();
}
}));
(0, _element.useEffect)(() => {
if (!ref.current) {
return;
}
const {
defaultView
} = ref.current.ownerDocument;
const {
name,
parent
} = defaultView;
const ownerDocument = name === 'editor-canvas' ? parent.document : defaultView.document;
const {
activeElement,
body
} = ownerDocument;
// Only autofocus the title when the post is entirely empty. This should
// only happen for a new post, which means we focus the title on new
// post so the author can start typing right away, without needing to
// click anything.
if (isCleanNewPost && (!activeElement || body === activeElement)) {
ref.current.focus();
}
}, [isCleanNewPost]);
return {
ref
};
}
//# sourceMappingURL=use-post-title-focus.js.map