@wordpress/block-library
Version:
Block library for the WordPress editor.
239 lines (238 loc) • 9.95 kB
JavaScript
import clsx from "clsx";
import { useDispatch, useSelect } from "@wordpress/data";
import { ToolbarButton, ToolbarGroup } from "@wordpress/components";
import { displayShortcut, isKeyboardEvent } from "@wordpress/keycodes";
import { __ } from "@wordpress/i18n";
import { BlockControls, InnerBlocks, InspectorControls, RichText, __experimentalGetShadowClassesAndStyles, getColorClassName, store, useBlockEditingMode, useBlockProps, useInnerBlocksProps } from "@wordpress/block-editor";
import { isURL, prependHTTP } from "@wordpress/url";
import { useEffect, useRef, useState } from "@wordpress/element";
import { link, removeSubmenu } from "@wordpress/icons";
import { speak } from "@wordpress/a11y";
import { createBlock } from "@wordpress/blocks";
import { useMergeRefs, usePrevious } from "@wordpress/compose";
import { ItemSubmenuIcon } from "./icons.mjs";
import { Controls, InvalidDraftDisplay, LinkUI, selectLabelText, useEnableLinkStatusValidation, useEntityBinding, useHandleLinkChange, useIsDraggingWithin, useIsInvalidLink } from "../navigation-link/shared/index.mjs";
import { getColors, getNavigationChildBlockProps } from "../navigation/edit/utils.mjs";
import { DEFAULT_BLOCK } from "../navigation/constants.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/block-library/src/navigation-submenu/edit.jsx
const ALLOWED_BLOCKS = [
"core/navigation-link",
"core/navigation-submenu",
"core/page-list",
"core/loginout"
];
/**
* @typedef {'post-type'|'custom'|'taxonomy'|'post-type-archive'} WPNavigationLinkKind
*/
/**
* Navigation Link Block Attributes
*
* @typedef {Object} WPNavigationLinkBlockAttributes
*
* @property {string} [label] Link text.
* @property {WPNavigationLinkKind} [kind] Kind is used to differentiate between term and post ids to check post draft status.
* @property {string} [type] The type such as post, page, tag, category and other custom types.
* @property {string} [rel] The relationship of the linked URL.
* @property {number} [id] A post or term id.
* @property {boolean} [opensInNewTab] Sets link target to _blank when true.
* @property {string} [url] Link href.
*/
function NavigationSubmenuEdit({ attributes, isSelected, setAttributes, mergeBlocks, onReplace, context, clientId }) {
const { label, url, description, kind, type, id } = attributes;
const { showSubmenuIcon, maxNestingLevel, submenuVisibility } = context;
const openSubmenusOnClick = useBlockEditingMode() !== "default" ? true : submenuVisibility === "click";
const { hasUrlBinding, isBoundEntityAvailable, entityRecord } = useEntityBinding({
clientId,
attributes
});
const handleLinkChange = useHandleLinkChange({
clientId,
attributes,
setAttributes,
allowTextUpdate: true
});
const { __unstableMarkNextChangeAsNotPersistent, replaceBlock } = useDispatch(store);
const [isLinkOpen, setIsLinkOpen] = useState(false);
const [popoverAnchor, setPopoverAnchor] = useState(null);
const listItemRef = useRef(null);
const isDraggingWithin = useIsDraggingWithin(listItemRef);
const itemLabelPlaceholder = __("Add text…");
const ref = useRef();
const { parentCount, isParentOfSelectedBlock, hasChildren, selectedBlockHasChildren, onlyDescendantIsEmptyLink } = useSelect((select) => {
const { hasSelectedInnerBlock, getSelectedBlockClientId, getBlockParentsByBlockName, getBlock, getBlockCount, getBlockOrder } = select(store);
let _onlyDescendantIsEmptyLink;
const selectedBlockChildren = getBlockOrder(getSelectedBlockClientId());
if (selectedBlockChildren?.length === 1) {
const singleBlock = getBlock(selectedBlockChildren[0]);
_onlyDescendantIsEmptyLink = singleBlock?.name === "core/navigation-link" && !singleBlock?.attributes?.label;
}
return {
parentCount: getBlockParentsByBlockName(clientId, "core/navigation-submenu").length,
isParentOfSelectedBlock: hasSelectedInnerBlock(clientId, true),
hasChildren: !!getBlockCount(clientId),
selectedBlockHasChildren: !!selectedBlockChildren?.length,
onlyDescendantIsEmptyLink: _onlyDescendantIsEmptyLink
};
}, [clientId]);
const validateLinkStatus = useEnableLinkStatusValidation(clientId);
const prevHasChildren = usePrevious(hasChildren);
const [isInvalid, isDraft] = useIsInvalidLink(kind, type, id, validateLinkStatus);
useEffect(() => {
if (!openSubmenusOnClick && !url) setIsLinkOpen(true);
}, []);
/**
* The hook shouldn't be necessary but due to a focus loss happening
* when selecting a suggestion in the link popover, we force close on block unselection.
*/
if (!isSelected && isLinkOpen) setIsLinkOpen(false);
useEffect(() => {
if (isLinkOpen && url) {
if (isURL(prependHTTP(label)) && /^.+\.[a-z]+/.test(label)) selectLabelText(ref);
}
}, [url]);
const { textColor, customTextColor, backgroundColor, customBackgroundColor } = getColors(context, parentCount > 0);
function onKeyDown(event) {
if (isKeyboardEvent.primary(event, "k")) {
event.preventDefault();
event.stopPropagation();
setIsLinkOpen(true);
}
}
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,
"open-on-click": openSubmenusOnClick,
"open-always": submenuVisibility === "always"
}),
style: {
color: !textColor && customTextColor,
backgroundColor: !backgroundColor && customBackgroundColor
},
onKeyDown
});
const innerBlocksColors = getColors(context, true);
const allowedBlocks = parentCount >= maxNestingLevel ? ALLOWED_BLOCKS.filter((blockName) => blockName !== "core/navigation-submenu") : ALLOWED_BLOCKS;
const shadowProps = __experimentalGetShadowClassesAndStyles(attributes);
const navigationChildBlockProps = getNavigationChildBlockProps(innerBlocksColors);
const submenuBlockProps = {
...navigationChildBlockProps,
style: {
...navigationChildBlockProps.style,
...shadowProps.style
}
};
const innerBlocksProps = useInnerBlocksProps(submenuBlockProps, {
allowedBlocks,
defaultBlock: DEFAULT_BLOCK,
directInsert: true,
__experimentalCaptureToolbars: true,
renderAppender: hasChildren ? InnerBlocks.DefaultBlockAppender : isSelected && InnerBlocks.ButtonBlockAppender
});
const ParentElement = openSubmenusOnClick ? "button" : "a";
function transformToLink() {
const newLinkBlock = createBlock("core/navigation-link", attributes);
replaceBlock(clientId, newLinkBlock);
}
useEffect(() => {
if (!hasChildren && prevHasChildren) {
__unstableMarkNextChangeAsNotPersistent();
transformToLink();
}
}, [hasChildren, prevHasChildren]);
const canConvertToLink = !selectedBlockHasChildren || onlyDescendantIsEmptyLink;
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(BlockControls, { children: /* @__PURE__ */ jsxs(ToolbarGroup, { children: [!openSubmenusOnClick && /* @__PURE__ */ jsx(ToolbarButton, {
name: "link",
icon: link,
title: __("Link"),
shortcut: displayShortcut.primary("k"),
onClick: () => {
setIsLinkOpen(true);
}
}), /* @__PURE__ */ jsx(ToolbarButton, {
name: "revert",
icon: removeSubmenu,
title: __("Convert to Link"),
onClick: transformToLink,
className: "wp-block-navigation__submenu__revert",
disabled: !canConvertToLink
})] }) }),
/* @__PURE__ */ jsx(InspectorControls, {
group: "content",
children: /* @__PURE__ */ jsx(Controls, {
attributes,
setAttributes,
clientId,
isLinkEditable: !openSubmenusOnClick
})
}),
/* @__PURE__ */ jsxs("div", {
...blockProps,
children: [
/* @__PURE__ */ jsxs(ParentElement, {
className: "wp-block-navigation-item__content",
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,
"aria-label": __("Navigation link text"),
placeholder: itemLabelPlaceholder,
withoutInteractiveFormatting: true,
onClick: () => {
if (!openSubmenusOnClick && !url) setIsLinkOpen(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-item__label"
}),
!openSubmenusOnClick && isLinkOpen && /* @__PURE__ */ jsx(LinkUI, {
clientId,
link: attributes,
entity: {
entityRecord,
hasBinding: hasUrlBinding,
isEntityAvailable: isBoundEntityAvailable
},
onClose: () => {
setIsLinkOpen(false);
},
anchor: popoverAnchor,
onRemove: () => {
setAttributes({ url: "" });
speak(__("Link removed."), "assertive");
},
onChange: handleLinkChange
})
]
}),
(showSubmenuIcon || openSubmenusOnClick) && /* @__PURE__ */ jsx("span", {
className: "wp-block-navigation__submenu-icon",
children: /* @__PURE__ */ jsx(ItemSubmenuIcon, {})
}),
/* @__PURE__ */ jsx("div", { ...innerBlocksProps })
]
})
] });
}
export { NavigationSubmenuEdit as default };
//# sourceMappingURL=edit.mjs.map