@wordpress/block-library
Version:
Block library for the WordPress editor.
71 lines (70 loc) • 2.9 kB
JavaScript
import { useCallback } from "@wordpress/element";
import { useDispatch } from "@wordpress/data";
import { store } from "@wordpress/block-editor";
import { __unstableStripHTML } from "@wordpress/dom";
import { escapeHTML } from "@wordpress/escape-html";
import { updateAttributes } from "./update-attributes.mjs";
import { useEntityBinding } from "./use-entity-binding.mjs";
// packages/block-library/src/navigation-link/shared/use-handle-link-change.js
/**
* Custom hook that returns a callback for handling link selection/change.
* Manages the transition between entity links and custom links,
* including proper binding creation and cleanup.
*
* @param {Object} options - Configuration options
* @param {string} options.clientId - Block client ID
* @param {Object} options.attributes - Current block attributes
* @param {Function} options.setAttributes - Standard setAttribute function
* @param {boolean} options.allowTextUpdate - Whether this control can update the link text
* @return {Function} Callback function to handle link changes
*/
function useHandleLinkChange({ clientId, attributes, setAttributes, allowTextUpdate = false }) {
const { updateBlockAttributes } = useDispatch(store);
const { hasUrlBinding, createBinding, clearBinding } = useEntityBinding({
clientId,
attributes
});
return useCallback((updatedLink) => {
if (!updatedLink) return;
const settingsUpdateAttributes = updatedLink.opensInNewTab !== void 0 ? { opensInNewTab: updatedLink.opensInNewTab } : {};
const attrs = {
url: updatedLink.url,
kind: updatedLink.kind,
type: updatedLink.type,
id: updatedLink.id,
...settingsUpdateAttributes
};
const currentText = attributes.label ? __unstableStripHTML(attributes.label) : "";
const updatedText = updatedLink.title ?? "";
const hasTextUpdate = allowTextUpdate && updatedLink.title !== void 0 && updatedText !== currentText;
const textUpdateAttributes = hasTextUpdate ? { label: escapeHTML(updatedText) } : {};
if (!attributes.label || attributes.label === "" || hasTextUpdate) attrs.title = updatedLink.title;
if (!updatedLink.id && hasUrlBinding) {
clearBinding();
updateBlockAttributes(clientId, {
url: updatedLink.url,
kind: "custom",
type: "custom",
id: void 0,
...settingsUpdateAttributes,
...textUpdateAttributes
});
} else {
const { isEntityLink, attributes: updatedAttributes } = updateAttributes(attrs, setAttributes, attributes);
if (isEntityLink) createBinding(updatedAttributes);
else clearBinding();
if (Object.keys(textUpdateAttributes).length) updateBlockAttributes(clientId, textUpdateAttributes);
}
}, [
attributes,
allowTextUpdate,
clientId,
hasUrlBinding,
createBinding,
clearBinding,
setAttributes,
updateBlockAttributes
]);
}
export { useHandleLinkChange };
//# sourceMappingURL=use-handle-link-change.mjs.map