UNPKG

@wordpress/block-editor

Version:
81 lines (75 loc) 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useBlockElement = useBlockElement; exports.useBlockElementRef = useBlockElementRef; exports.useBlockRefProvider = useBlockRefProvider; var _element = require("@wordpress/element"); var _compose = require("@wordpress/compose"); var _blockRefsProvider = require("../../provider/block-refs-provider"); /** * WordPress dependencies */ /** * Internal dependencies */ /** @typedef {import('@wordpress/element').RefCallback} RefCallback */ /** @typedef {import('@wordpress/element').Ref} Ref */ /** * Provides a ref to the BlockRefs context. * * @param {string} clientId The client ID of the element ref. * * @return {RefCallback} Ref callback. */ function useBlockRefProvider(clientId) { const { refsMap } = (0, _element.useContext)(_blockRefsProvider.BlockRefs); return (0, _compose.useRefEffect)(element => { refsMap.set(clientId, element); return () => refsMap.delete(clientId); }, [clientId]); } function assignRef(ref, value) { if (typeof ref === 'function') { ref(value); } else if (ref) { ref.current = value; } } /** * Tracks the DOM element for the block identified by `clientId` and assigns it to the `ref` * whenever it changes. * * @param {string} clientId The client ID to track. * @param {Ref} ref The ref object/callback to assign to. */ function useBlockElementRef(clientId, ref) { const { refsMap } = (0, _element.useContext)(_blockRefsProvider.BlockRefs); (0, _element.useLayoutEffect)(() => { assignRef(ref, refsMap.get(clientId)); const unsubscribe = refsMap.subscribe(clientId, () => assignRef(ref, refsMap.get(clientId))); return () => { unsubscribe(); assignRef(ref, null); }; }, [refsMap, clientId, ref]); } /** * Return the element for a given client ID. Updates whenever the element * changes, becomes available, or disappears. * * @param {string} clientId The client ID to an element for. * * @return {Element|null} The block's wrapper element. */ function useBlockElement(clientId) { const [blockElement, setBlockElement] = (0, _element.useState)(null); useBlockElementRef(clientId, setBlockElement); return blockElement; } //# sourceMappingURL=use-block-refs.js.map