UNPKG

@wordpress/block-library

Version:
373 lines (372 loc) • 14.1 kB
import clsx from "clsx"; import { __, sprintf } from "@wordpress/i18n"; import { createInterpolateElement, useMemo, useRef, useState } from "@wordpress/element"; import { Popover, TextControl, ToolbarButton, __experimentalToolsPanel, __experimentalToolsPanelItem } from "@wordpress/components"; import { BlockControls, InspectorControls, LinkControl, RichText, __experimentalGetDimensionsClassesAndStyles, __experimentalGetElementClassName, __experimentalGetShadowClassesAndStyles, __experimentalGetSpacingClassesAndStyles, __experimentalUseBorderProps, __experimentalUseColorProps, getTypographyClassesAndStyles, privateApis, store, useBackgroundProps, useBlockEditingMode, useBlockProps, useSettings } from "@wordpress/block-editor"; import { ENTER, displayShortcut, isKeyboardEvent } from "@wordpress/keycodes"; import { link } from "@wordpress/icons"; import { __unstableStripHTML } from "@wordpress/dom"; import { cloneBlock, createBlock, getBlockBindingsSource, getDefaultBlockName } from "@wordpress/blocks"; import { privateApis as privateApis$1, useMergeRefs, useRefEffect } from "@wordpress/compose"; import { useDispatch, useSelect } from "@wordpress/data"; import { CheckboxControl, Link } from "@wordpress/ui"; import { NEW_TAB_TARGET, NOFOLLOW_REL } from "./constants.mjs"; import { getUpdatedLinkAttributes } from "./get-updated-link-attributes.mjs"; import removeAnchorTag from "../utils/remove-anchor-tag.mjs"; import { useToolsPanelDropdownMenuProps } from "../utils/hooks.mjs"; import { getSuggestionsQuery, useLinkPreview } from "../utils/link-picker.mjs"; import ViewLinkButton from "../utils/view-link-button.mjs"; import { unlock } from "../lock-unlock.mjs"; import useDeprecatedTextAlign from "../utils/deprecated-text-align-attributes.mjs"; import { getWidthClasses, isPercentageWidth } from "./utils.mjs"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; // packages/block-library/src/button/edit.jsx const { HTMLElementControl, LinkPicker } = unlock(privateApis); const { subscribeDelegatedListener } = unlock(privateApis$1); const LINK_SETTINGS = [...LinkControl.DEFAULT_LINK_SETTINGS, { id: "nofollow", title: __("Mark as nofollow") }]; function useEnter(clientId) { const { replaceBlocks, selectionChange } = useDispatch(store); const { getBlock, getBlockAttributes, getBlockRootClientId, getBlockIndex } = useSelect(store); return useRefEffect((element) => { function onKeyDown(event) { if (event.defaultPrevented || event.keyCode !== ENTER) return; const { text } = getBlockAttributes(clientId) ?? {}; if (text?.length) return; event.preventDefault(); const topParentListBlock = getBlock(getBlockRootClientId(clientId)); const blockIndex = getBlockIndex(clientId); const head = cloneBlock({ ...topParentListBlock, innerBlocks: topParentListBlock.innerBlocks.slice(0, blockIndex) }); const middle = createBlock(getDefaultBlockName()); const after = topParentListBlock.innerBlocks.slice(blockIndex + 1); const tail = after.length ? [cloneBlock({ ...topParentListBlock, innerBlocks: after })] : []; replaceBlocks(topParentListBlock.clientId, [ head, middle, ...tail ], 1); selectionChange(middle.clientId); } return subscribeDelegatedListener(element, "keydown", onKeyDown, true); }, []); } /** * The content controls shown in the block inspector's Content tab and in the * List View popover, mirroring the Navigation Link block's panel. * * The canvas, the link popover, and this panel all write through the same * `setText`, `setLink`, and `unlink` so the three surfaces can't drift. * * @param {Object} props * @param {string} props.text The button text. * @param {string} props.url The button link. * @param {boolean} props.opensInNewTab Whether the link opens in a new tab. * @param {boolean} props.isTextEditable Whether the text field is enabled. * @param {boolean} props.isLinkEditable Whether the link fields are shown. * @param {( text: string ) => void} props.setText Updates the button text. * @param {( link: Object ) => void} props.setLink Updates the link, new tab, and nofollow attributes. * @param {() => void} props.unlink Removes the link and its attributes. */ function ContentControls({ text, url, opensInNewTab, isTextEditable, isLinkEditable, setText, setLink, unlink }) { const dropdownMenuProps = useToolsPanelDropdownMenuProps(); const preview = useLinkPreview({ url }); return /* @__PURE__ */ jsxs(__experimentalToolsPanel, { label: __("Settings"), resetAll: () => { setText(""); unlink(); }, dropdownMenuProps, children: [/* @__PURE__ */ jsx(__experimentalToolsPanelItem, { hasValue: () => !!text?.length, label: __("Text"), onDeselect: () => setText(""), isShownByDefault: true, children: /* @__PURE__ */ jsx(TextControl, { label: __("Text"), value: text ? __unstableStripHTML(text.toString()) : "", onChange: setText, disabled: !isTextEditable, autoComplete: "off" }) }), isLinkEditable && /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { hasValue: () => !!url, label: __("Link to"), onDeselect: unlink, isShownByDefault: true, children: /* @__PURE__ */ jsx(LinkPicker, { preview, onSelect: ({ url: newUrl }) => setLink({ url: newUrl }), suggestionsQuery: getSuggestionsQuery(), label: __("Link to") }) }), url && /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { hasValue: () => opensInNewTab, label: __("Open in new tab"), onDeselect: () => setLink({ opensInNewTab: false }), isShownByDefault: true, children: /* @__PURE__ */ jsx(CheckboxControl, { label: __("Open in new tab"), checked: opensInNewTab, onCheckedChange: (value) => setLink({ opensInNewTab: value }) }) }), /* @__PURE__ */ jsx(ViewLinkButton, { url }) ] })] }); } function ButtonEdit(props) { const { attributes, setAttributes, className, isSelected, onReplace, mergeBlocks, clientId, context } = props; const { tagName, linkTarget, placeholder, rel, style, text, url, metadata } = attributes; const width = style?.dimensions?.width; useDeprecatedTextAlign(props); const TagName = tagName || "a"; function onKeyDown(event) { if (isKeyboardEvent.primary(event, "k")) startEditing(event); else if (isKeyboardEvent.primaryShift(event, "k")) { unlink(); richTextRef.current?.focus(); } } const [popoverAnchor, setPopoverAnchor] = useState(null); const borderProps = __experimentalUseBorderProps(attributes); const colorProps = __experimentalUseColorProps(attributes); const spacingProps = __experimentalGetSpacingClassesAndStyles(attributes); const shadowProps = __experimentalGetShadowClassesAndStyles(attributes); const backgroundProps = useBackgroundProps(attributes); const dimensionsProps = __experimentalGetDimensionsClassesAndStyles(attributes); const ref = useRef(); const richTextRef = useRef(); const blockProps = useBlockProps({ ref: useMergeRefs([setPopoverAnchor, ref]), onKeyDown }); const blockEditingMode = useBlockEditingMode(); const isInsideNavigation = useSelect((select) => !!select(store).getBlockParentsByBlockName(clientId, "core/navigation").length, [clientId]); const hasContentControls = blockEditingMode === "contentOnly" || isInsideNavigation; const [isEditingURL, setIsEditingURL] = useState(false); const isURLSet = !!url; const opensInNewTab = linkTarget === NEW_TAB_TARGET; const nofollow = !!rel?.includes(NOFOLLOW_REL); const isLinkTag = "a" === TagName; const { createPageEntity, userCanCreatePages, lockUrlControls = false, lockTextControls = false } = useSelect((select) => { if (!isSelected) return {}; const _settings = select(store).getSettings(); const isLocked = (binding) => !!binding && !getBlockBindingsSource(binding.source)?.canUserEditValue?.({ select, context, args: binding.args }); return { createPageEntity: _settings.__experimentalCreatePageEntity, userCanCreatePages: _settings.__experimentalUserCanCreatePages, lockUrlControls: isLocked(metadata?.bindings?.url), lockTextControls: isLocked(metadata?.bindings?.text) }; }, [ context, isSelected, metadata?.bindings?.url, metadata?.bindings?.text ]); async function handleCreate(pageTitle) { const page = await createPageEntity({ title: pageTitle, status: "draft" }); return { id: page.id, type: page.type, title: page.title.rendered, url: page.link, kind: "post-type" }; } function createButtonText(searchTerm) { return createInterpolateElement(sprintf(__("Create page: <mark>%s</mark>"), searchTerm), { mark: /* @__PURE__ */ jsx("mark", {}) }); } function startEditing(event) { event.preventDefault(); setIsEditingURL(true); } function setText(value) { setAttributes({ text: removeAnchorTag(value) }); } function setLink(changes) { setAttributes(getUpdatedLinkAttributes({ rel, url, opensInNewTab, nofollow, ...changes })); } function unlink() { setAttributes({ url: void 0, linkTarget: void 0, rel: void 0 }); setIsEditingURL(false); } if (!isSelected && isEditingURL) setIsEditingURL(false); const linkValue = useMemo(() => ({ url, opensInNewTab, nofollow }), [ url, opensInNewTab, nofollow ]); const useEnterRef = useEnter(clientId); const mergedRef = useMergeRefs([useEnterRef, richTextRef]); const [fluidTypographySettings, layout, dimensionSizes] = useSettings("typography.fluid", "layout", "dimensions.dimensionSizes"); const dimensionPresets = useMemo(() => { if (!dimensionSizes) return []; return [ ...dimensionSizes?.custom ?? [], ...dimensionSizes?.theme ?? [], ...dimensionSizes?.default ?? [] ]; }, [dimensionSizes]); const typographyProps = getTypographyClassesAndStyles(attributes, { typography: { fluid: fluidTypographySettings }, layout: { wideSize: layout?.wideSize } }); const resolvedWidth = useMemo(() => { if (!width) return; if (width.startsWith("var:preset|dimension|")) { const slug = width.slice(21); return (dimensionPresets?.find((p) => p.slug === slug))?.size ?? width; } return width; }, [width, dimensionPresets]); const hasBlockControls = blockEditingMode === "default" || isLinkTag && !lockUrlControls; const classes = clsx(blockProps.className, getWidthClasses(resolvedWidth)); const widthStyle = useMemo(() => { if (!width) return {}; if (isPercentageWidth(resolvedWidth)) return { "--wp--block-button--width": parseFloat(resolvedWidth) }; return dimensionsProps.style; }, [ width, resolvedWidth, dimensionsProps.style ]); return /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx("div", { ...blockProps, className: classes, style: { ...blockProps.style, ...widthStyle }, children: /* @__PURE__ */ jsx(RichText, { ref: mergedRef, "aria-label": __("Button text"), placeholder: placeholder || __("Add text…"), value: text, onChange: setText, withoutInteractiveFormatting: true, className: clsx(className, "wp-block-button__link", colorProps.className, backgroundProps.className, borderProps.className, typographyProps.className, { "no-border-radius": style?.border?.radius === 0, [`has-custom-font-size`]: blockProps.style.fontSize }, __experimentalGetElementClassName("button")), style: { ...borderProps.style, ...colorProps.style, ...backgroundProps.style, ...spacingProps.style, ...shadowProps.style, ...typographyProps.style, writingMode: void 0 }, onReplace, onMerge: mergeBlocks, identifier: "text" }) }), hasBlockControls && /* @__PURE__ */ jsx(BlockControls, { group: "block", children: isLinkTag && !lockUrlControls && /* @__PURE__ */ jsx(ToolbarButton, { name: "link", icon: link, title: __("Link"), shortcut: displayShortcut.primary("k"), onClick: () => setIsEditingURL(!isEditingURL), isActive: isURLSet }) }), isLinkTag && isSelected && isEditingURL && !lockUrlControls && /* @__PURE__ */ jsx(Popover, { placement: "bottom", onClose: () => { setIsEditingURL(false); richTextRef.current?.focus(); }, anchor: popoverAnchor, focusOnMount: isEditingURL ? "firstElement" : false, __unstableSlotName: "__unstable-block-tools-after", shift: true, children: /* @__PURE__ */ jsx(LinkControl, { value: linkValue, onChange: setLink, onRemove: () => { unlink(); richTextRef.current?.focus(); }, forceIsEditingLink: !isURLSet, settings: LINK_SETTINGS, createSuggestion: createPageEntity && handleCreate, withCreateSuggestion: userCanCreatePages, createSuggestionButtonText: createButtonText }) }), hasContentControls && /* @__PURE__ */ jsx(InspectorControls, { group: "content", children: /* @__PURE__ */ jsx(ContentControls, { text, url, opensInNewTab, isTextEditable: !lockTextControls, isLinkEditable: isLinkTag && !lockUrlControls, setText, setLink, unlink }) }), /* @__PURE__ */ jsxs(InspectorControls, { group: "advanced", children: [/* @__PURE__ */ jsx(HTMLElementControl, { tagName, onChange: (value) => setAttributes({ tagName: value }), options: [{ label: __("Default (<a>)"), value: "a" }, { label: "<button>", value: "button" }] }), isLinkTag && /* @__PURE__ */ jsx(TextControl, { label: __("Link relation"), help: createInterpolateElement(__("The <a>Link Relation</a> attribute defines the relationship between a linked resource and the current document."), { a: /* @__PURE__ */ jsx(Link, { openInNewTab: true, href: "https://developer.mozilla.org/docs/Web/HTML/Attributes/rel" }) }), value: rel || "", onChange: (newRel) => setAttributes({ rel: newRel }) })] }) ] }); } export { ButtonEdit as default }; //# sourceMappingURL=edit.mjs.map