@wordpress/block-library
Version:
Block library for the WordPress editor.
284 lines (283 loc) • 10.9 kB
JavaScript
import clsx from "clsx";
import { createBlock } from "@wordpress/blocks";
import { useDispatch, useSelect } from "@wordpress/data";
import { ToolbarButton, ToolbarGroup } from "@wordpress/components";
import { displayShortcut, isKeyboardEvent } from "@wordpress/keycodes";
import { __, sprintf } from "@wordpress/i18n";
import { BlockControls, InspectorControls, RichText, getColorClassName, store, useBlockProps, useInnerBlocksProps } from "@wordpress/block-editor";
import { isURL, prependHTTP } from "@wordpress/url";
import { useCallback, useEffect, useRef, useState } from "@wordpress/element";
import { VisuallyHidden } from "@wordpress/ui";
import { addSubmenu, link } from "@wordpress/icons";
import { useInstanceId, useMergeRefs } from "@wordpress/compose";
import { getColors } from "../navigation/edit/utils.mjs";
import { Controls, InvalidDraftDisplay, LinkUI, getInvalidLinkHelpText, selectLabelText, useEnableLinkStatusValidation, useEntityBinding, useHandleLinkChange, useIsDraggingWithin, useIsInvalidLink } from "./shared/index.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/block-library/src/navigation-link/edit.jsx
const DEFAULT_BLOCK = { name: "core/navigation-link" };
const NESTING_BLOCK_NAMES = ["core/navigation-link", "core/navigation-submenu"];
/**
* Focuses the appender of the block list that contains the given element.
*
* The parent's appender changes from the button appender to the dropdown
* appender once it has items, so the appender that opened the Link UI may no
* longer be there to receive focus when the Link UI closes.
*
* @param {?Element} container The block list container element.
*/
function focusAppender(container) {
container?.querySelector(":scope > .block-list-appender button")?.focus();
}
function getMissingText(type) {
let missingText = "";
switch (type) {
case "post":
missingText = __("Select post");
break;
case "page":
missingText = __("Select page");
break;
case "category":
missingText = __("Select category");
break;
case "tag":
missingText = __("Select tag");
break;
default: missingText = __("Add link");
}
return missingText;
}
function NavigationLinkEdit({ attributes, isSelected, setAttributes, insertBlocksAfter, mergeBlocks, onReplace, context, clientId }) {
const { id, label, type, url, description, kind, metadata } = attributes;
const { maxNestingLevel } = context;
const { replaceBlock, __unstableMarkNextChangeAsNotPersistent, selectBlock } = useDispatch(store);
const [isLinkOpen, setIsLinkOpen] = useState(isSelected && !url);
const [popoverAnchor, setPopoverAnchor] = useState(null);
const listItemRef = useRef(null);
const isDraggingWithin = useIsDraggingWithin(listItemRef);
const itemLabelPlaceholder = __("Add label…");
const ref = useRef();
const linkUIref = useRef();
const isNewLink = useRef(label === void 0);
const shouldFocusAppenderOnClose = useRef(false);
const { isAtMaxNesting, isTopLevelLink, isParentOfSelectedBlock, hasChildren, parentBlockClientId } = useSelect((select) => {
const { getBlockCount, getBlockName, getBlockRootClientId, hasSelectedInnerBlock, getBlockParentsByBlockName } = select(store);
const rootClientId = getBlockRootClientId(clientId);
const parentBlockName = getBlockName(rootClientId);
const isTopLevel = parentBlockName === "core/navigation";
const rootNavigationClientId = isTopLevel ? rootClientId : getBlockParentsByBlockName(clientId, "core/navigation")[0];
const parentBlockId = parentBlockName === "core/navigation-submenu" ? rootClientId : rootNavigationClientId;
return {
isAtMaxNesting: getBlockParentsByBlockName(clientId, NESTING_BLOCK_NAMES).length >= maxNestingLevel,
isTopLevelLink: isTopLevel,
isParentOfSelectedBlock: hasSelectedInnerBlock(clientId, true),
hasChildren: !!getBlockCount(clientId),
parentBlockClientId: parentBlockId
};
}, [clientId, maxNestingLevel]);
const validateLinkStatus = useEnableLinkStatusValidation(clientId);
const { getBlocks } = useSelect(store);
const { hasUrlBinding, isBoundEntityAvailable, entityRecord } = useEntityBinding({
clientId,
attributes
});
const handleLinkChange = useHandleLinkChange({
clientId,
attributes,
setAttributes,
allowTextUpdate: true
});
const [isInvalid, isDraft] = useIsInvalidLink(kind, type, id, validateLinkStatus);
/**
* Transform to submenu block.
*/
const transformToSubmenu = useCallback(() => {
let innerBlocks = getBlocks(clientId);
if (innerBlocks.length === 0) {
innerBlocks = [createBlock("core/navigation-link")];
selectBlock(innerBlocks[0].clientId);
}
const newSubmenu = createBlock("core/navigation-submenu", attributes, innerBlocks);
replaceBlock(clientId, newSubmenu);
}, [
getBlocks,
clientId,
selectBlock,
replaceBlock,
attributes
]);
useEffect(() => {
if (isNewLink.current && isSelected) selectBlock(parentBlockClientId);
}, []);
useEffect(() => {
if (hasChildren) {
__unstableMarkNextChangeAsNotPersistent();
transformToSubmenu();
}
}, [
hasChildren,
__unstableMarkNextChangeAsNotPersistent,
transformToSubmenu
]);
useEffect(() => {
if (!isNewLink.current || !url || !isLinkOpen) return;
isNewLink.current = false;
if (isURL(prependHTTP(label)) && /^.+\.[a-z]+/.test(label)) selectLabelText(ref);
else {
selectBlock(clientId, null);
const parentBlocks = getBlocks(parentBlockClientId);
if (parentBlocks.length === 1 && parentBlocks[0].clientId === clientId) shouldFocusAppenderOnClose.current = true;
}
}, [
url,
isLinkOpen,
isNewLink,
label
]);
/**
* Removes the current link if set.
*/
function removeLink() {
setAttributes({
url: void 0,
label: void 0,
id: void 0,
kind: void 0,
type: void 0,
opensInNewTab: false
});
setIsLinkOpen(false);
}
const { textColor, customTextColor, backgroundColor, customBackgroundColor } = getColors(context, !isTopLevelLink);
function onKeyDown(event) {
if (isKeyboardEvent.primary(event, "k")) {
event.preventDefault();
event.stopPropagation();
setIsLinkOpen(true);
}
}
const instanceId = useInstanceId(NavigationLinkEdit);
const hasMissingEntity = hasUrlBinding && !isBoundEntityAvailable;
const missingEntityDescriptionId = hasMissingEntity ? sprintf("navigation-link-edit-%d-desc", instanceId) : void 0;
const blockProps = useBlockProps({
ref: useMergeRefs([setPopoverAnchor, listItemRef]),
className: clsx("wp-block-navigation-item", {
"is-editing": isSelected || isParentOfSelectedBlock,
"is-dragging-within": isDraggingWithin,
"has-link": !!url,
"has-child": hasChildren,
"has-text-color": !!textColor || !!customTextColor,
[getColorClassName("color", textColor)]: !!textColor,
"has-background": !!backgroundColor || customBackgroundColor,
[getColorClassName("background-color", backgroundColor)]: !!backgroundColor
}),
"aria-describedby": missingEntityDescriptionId,
"aria-invalid": hasMissingEntity,
style: {
color: !textColor && customTextColor,
backgroundColor: !backgroundColor && customBackgroundColor
},
onKeyDown
});
const innerBlocksProps = useInnerBlocksProps({ className: "remove-outline" }, {
defaultBlock: DEFAULT_BLOCK,
directInsert: true,
renderAppender: false
});
const needsValidLink = !url && !(hasUrlBinding && isBoundEntityAvailable) || isInvalid || isDraft || hasUrlBinding && !isBoundEntityAvailable;
if (needsValidLink) blockProps.onClick = () => {
setIsLinkOpen(true);
};
const classes = clsx("wp-block-navigation-item__content", { "wp-block-navigation-link__placeholder": needsValidLink });
const missingText = getMissingText(type);
const invalidLinkHelpText = getInvalidLinkHelpText();
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(BlockControls, { children: /* @__PURE__ */ jsxs(ToolbarGroup, { children: [/* @__PURE__ */ jsx(ToolbarButton, {
name: "link",
icon: link,
title: __("Link"),
shortcut: displayShortcut.primary("k"),
onClick: () => {
setIsLinkOpen(true);
}
}), !isAtMaxNesting && /* @__PURE__ */ jsx(ToolbarButton, {
name: "submenu",
icon: addSubmenu,
title: __("Add submenu"),
onClick: transformToSubmenu
})] }) }),
/* @__PURE__ */ jsx(InspectorControls, {
group: "content",
children: /* @__PURE__ */ jsx(Controls, {
attributes,
setAttributes,
clientId
})
}),
/* @__PURE__ */ jsxs("div", {
...blockProps,
children: [
hasMissingEntity && /* @__PURE__ */ jsx(VisuallyHidden, {
id: missingEntityDescriptionId,
children: invalidLinkHelpText
}),
/* @__PURE__ */ jsxs("a", {
className: classes,
children: [!url && !metadata?.bindings?.url ? /* @__PURE__ */ jsx("div", {
className: "wp-block-navigation-link__placeholder-text",
children: /* @__PURE__ */ jsx("span", { children: missingText })
}) : /* @__PURE__ */ jsxs(Fragment, { children: [!isInvalid && !isDraft && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(RichText, {
ref,
identifier: "label",
className: "wp-block-navigation-item__label",
value: label,
onChange: (labelValue) => setAttributes({ label: labelValue }),
onMerge: mergeBlocks,
onReplace,
__unstableOnSplitAtEnd: insertBlocksAfter ? () => insertBlocksAfter(createBlock("core/navigation-link")) : void 0,
"aria-label": __("Navigation link text"),
placeholder: itemLabelPlaceholder,
withoutInteractiveFormatting: true
}), description && /* @__PURE__ */ jsx("span", {
className: "wp-block-navigation-item__description",
children: description
})] }), (isInvalid || isDraft) && /* @__PURE__ */ jsx(InvalidDraftDisplay, {
label,
isInvalid,
isDraft,
className: "wp-block-navigation-link__label"
})] }), isLinkOpen && /* @__PURE__ */ jsx(LinkUI, {
ref: linkUIref,
clientId,
link: attributes,
entity: {
entityRecord,
hasBinding: hasUrlBinding,
isEntityAvailable: isBoundEntityAvailable
},
onClose: () => {
setIsLinkOpen(false);
if (!url && !hasUrlBinding && onReplace) {
const container = listItemRef.current?.parentElement;
const isOnlyChild = getBlocks(parentBlockClientId).length === 1;
onReplace([]);
if (isOnlyChild) container?.ownerDocument.defaultView.requestAnimationFrame(() => focusAppender(container));
return;
}
if (shouldFocusAppenderOnClose.current) {
shouldFocusAppenderOnClose.current = false;
focusAppender(listItemRef.current?.parentElement);
}
},
anchor: popoverAnchor,
onRemove: removeLink,
onChange: handleLinkChange
})]
}),
/* @__PURE__ */ jsx("div", { ...innerBlocksProps })
]
})
] });
}
export { NavigationLinkEdit as default };
//# sourceMappingURL=edit.mjs.map