@wordpress/block-library
Version:
Block library for the WordPress editor.
403 lines (402 loc) • 17.6 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
// \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
let clsx = require("clsx");
clsx = __toESM(clsx);
let _wordpress_i18n = require("@wordpress/i18n");
let _wordpress_element = require("@wordpress/element");
let _wordpress_components = require("@wordpress/components");
let _wordpress_block_editor = require("@wordpress/block-editor");
let _wordpress_keycodes = require("@wordpress/keycodes");
let _wordpress_icons = require("@wordpress/icons");
let _wordpress_dom = require("@wordpress/dom");
let _wordpress_blocks = require("@wordpress/blocks");
let _wordpress_compose = require("@wordpress/compose");
let _wordpress_data = require("@wordpress/data");
let _wordpress_ui = require("@wordpress/ui");
let __constants_js = require("./constants.cjs");
let __get_updated_link_attributes_js = require("./get-updated-link-attributes.cjs");
let ___utils_remove_anchor_tag_js = require("../utils/remove-anchor-tag.cjs");
___utils_remove_anchor_tag_js = __toESM(___utils_remove_anchor_tag_js);
let ___utils_hooks_js = require("../utils/hooks.cjs");
let ___utils_link_picker_ts = require("../utils/link-picker.cjs");
let ___utils_view_link_button_tsx = require("../utils/view-link-button.cjs");
___utils_view_link_button_tsx = __toESM(___utils_view_link_button_tsx);
let ___lock_unlock_ts = require("../lock-unlock.cjs");
let ___utils_deprecated_text_align_attributes_js = require("../utils/deprecated-text-align-attributes.cjs");
___utils_deprecated_text_align_attributes_js = __toESM(___utils_deprecated_text_align_attributes_js);
let __utils_js = require("./utils.cjs");
let react_jsx_runtime = require("react/jsx-runtime");
// packages/block-library/src/button/edit.jsx
const { HTMLElementControl, LinkPicker } = (0, ___lock_unlock_ts.unlock)(_wordpress_block_editor.privateApis);
const { subscribeDelegatedListener } = (0, ___lock_unlock_ts.unlock)(_wordpress_compose.privateApis);
const LINK_SETTINGS = [..._wordpress_block_editor.LinkControl.DEFAULT_LINK_SETTINGS, {
id: "nofollow",
title: (0, _wordpress_i18n.__)("Mark as nofollow")
}];
function useEnter(clientId) {
const { replaceBlocks, selectionChange } = (0, _wordpress_data.useDispatch)(_wordpress_block_editor.store);
const { getBlock, getBlockAttributes, getBlockRootClientId, getBlockIndex } = (0, _wordpress_data.useSelect)(_wordpress_block_editor.store);
return (0, _wordpress_compose.useRefEffect)((element) => {
function onKeyDown(event) {
if (event.defaultPrevented || event.keyCode !== _wordpress_keycodes.ENTER) return;
const { text } = getBlockAttributes(clientId) ?? {};
if (text?.length) return;
event.preventDefault();
const topParentListBlock = getBlock(getBlockRootClientId(clientId));
const blockIndex = getBlockIndex(clientId);
const head = (0, _wordpress_blocks.cloneBlock)({
...topParentListBlock,
innerBlocks: topParentListBlock.innerBlocks.slice(0, blockIndex)
});
const middle = (0, _wordpress_blocks.createBlock)((0, _wordpress_blocks.getDefaultBlockName)());
const after = topParentListBlock.innerBlocks.slice(blockIndex + 1);
const tail = after.length ? [(0, _wordpress_blocks.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 = (0, ___utils_hooks_js.useToolsPanelDropdownMenuProps)();
const preview = (0, ___utils_link_picker_ts.useLinkPreview)({ url });
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_components.__experimentalToolsPanel, {
label: (0, _wordpress_i18n.__)("Settings"),
resetAll: () => {
setText("");
unlink();
},
dropdownMenuProps,
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.__experimentalToolsPanelItem, {
hasValue: () => !!text?.length,
label: (0, _wordpress_i18n.__)("Text"),
onDeselect: () => setText(""),
isShownByDefault: true,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.TextControl, {
label: (0, _wordpress_i18n.__)("Text"),
value: text ? (0, _wordpress_dom.__unstableStripHTML)(text.toString()) : "",
onChange: setText,
disabled: !isTextEditable,
autoComplete: "off"
})
}), isLinkEditable && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.__experimentalToolsPanelItem, {
hasValue: () => !!url,
label: (0, _wordpress_i18n.__)("Link to"),
onDeselect: unlink,
isShownByDefault: true,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LinkPicker, {
preview,
onSelect: ({ url: newUrl }) => setLink({ url: newUrl }),
suggestionsQuery: (0, ___utils_link_picker_ts.getSuggestionsQuery)(),
label: (0, _wordpress_i18n.__)("Link to")
})
}),
url && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.__experimentalToolsPanelItem, {
hasValue: () => opensInNewTab,
label: (0, _wordpress_i18n.__)("Open in new tab"),
onDeselect: () => setLink({ opensInNewTab: false }),
isShownByDefault: true,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.CheckboxControl, {
label: (0, _wordpress_i18n.__)("Open in new tab"),
checked: opensInNewTab,
onCheckedChange: (value) => setLink({ opensInNewTab: value })
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(___utils_view_link_button_tsx.default, { 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;
(0, ___utils_deprecated_text_align_attributes_js.default)(props);
const TagName = tagName || "a";
function onKeyDown(event) {
if (_wordpress_keycodes.isKeyboardEvent.primary(event, "k")) startEditing(event);
else if (_wordpress_keycodes.isKeyboardEvent.primaryShift(event, "k")) {
unlink();
richTextRef.current?.focus();
}
}
const [popoverAnchor, setPopoverAnchor] = (0, _wordpress_element.useState)(null);
const borderProps = (0, _wordpress_block_editor.__experimentalUseBorderProps)(attributes);
const colorProps = (0, _wordpress_block_editor.__experimentalUseColorProps)(attributes);
const spacingProps = (0, _wordpress_block_editor.__experimentalGetSpacingClassesAndStyles)(attributes);
const shadowProps = (0, _wordpress_block_editor.__experimentalGetShadowClassesAndStyles)(attributes);
const backgroundProps = (0, _wordpress_block_editor.useBackgroundProps)(attributes);
const dimensionsProps = (0, _wordpress_block_editor.__experimentalGetDimensionsClassesAndStyles)(attributes);
const ref = (0, _wordpress_element.useRef)();
const richTextRef = (0, _wordpress_element.useRef)();
const blockProps = (0, _wordpress_block_editor.useBlockProps)({
ref: (0, _wordpress_compose.useMergeRefs)([setPopoverAnchor, ref]),
onKeyDown
});
const blockEditingMode = (0, _wordpress_block_editor.useBlockEditingMode)();
const isInsideNavigation = (0, _wordpress_data.useSelect)((select) => !!select(_wordpress_block_editor.store).getBlockParentsByBlockName(clientId, "core/navigation").length, [clientId]);
const hasContentControls = blockEditingMode === "contentOnly" || isInsideNavigation;
const [isEditingURL, setIsEditingURL] = (0, _wordpress_element.useState)(false);
const isURLSet = !!url;
const opensInNewTab = linkTarget === __constants_js.NEW_TAB_TARGET;
const nofollow = !!rel?.includes(__constants_js.NOFOLLOW_REL);
const isLinkTag = "a" === TagName;
const { createPageEntity, userCanCreatePages, lockUrlControls = false, lockTextControls = false } = (0, _wordpress_data.useSelect)((select) => {
if (!isSelected) return {};
const _settings = select(_wordpress_block_editor.store).getSettings();
const isLocked = (binding) => !!binding && !(0, _wordpress_blocks.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 (0, _wordpress_element.createInterpolateElement)((0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Create page: <mark>%s</mark>"), searchTerm), { mark: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("mark", {}) });
}
function startEditing(event) {
event.preventDefault();
setIsEditingURL(true);
}
function setText(value) {
setAttributes({ text: (0, ___utils_remove_anchor_tag_js.default)(value) });
}
function setLink(changes) {
setAttributes((0, __get_updated_link_attributes_js.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 = (0, _wordpress_element.useMemo)(() => ({
url,
opensInNewTab,
nofollow
}), [
url,
opensInNewTab,
nofollow
]);
const useEnterRef = useEnter(clientId);
const mergedRef = (0, _wordpress_compose.useMergeRefs)([useEnterRef, richTextRef]);
const [fluidTypographySettings, layout, dimensionSizes] = (0, _wordpress_block_editor.useSettings)("typography.fluid", "layout", "dimensions.dimensionSizes");
const dimensionPresets = (0, _wordpress_element.useMemo)(() => {
if (!dimensionSizes) return [];
return [
...dimensionSizes?.custom ?? [],
...dimensionSizes?.theme ?? [],
...dimensionSizes?.default ?? []
];
}, [dimensionSizes]);
const typographyProps = (0, _wordpress_block_editor.getTypographyClassesAndStyles)(attributes, {
typography: { fluid: fluidTypographySettings },
layout: { wideSize: layout?.wideSize }
});
const resolvedWidth = (0, _wordpress_element.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 = (0, clsx.default)(blockProps.className, (0, __utils_js.getWidthClasses)(resolvedWidth));
const widthStyle = (0, _wordpress_element.useMemo)(() => {
if (!width) return {};
if ((0, __utils_js.isPercentageWidth)(resolvedWidth)) return { "--wp--block-button--width": parseFloat(resolvedWidth) };
return dimensionsProps.style;
}, [
width,
resolvedWidth,
dimensionsProps.style
]);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
...blockProps,
className: classes,
style: {
...blockProps.style,
...widthStyle
},
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_block_editor.RichText, {
ref: mergedRef,
"aria-label": (0, _wordpress_i18n.__)("Button text"),
placeholder: placeholder || (0, _wordpress_i18n.__)("Add text…"),
value: text,
onChange: setText,
withoutInteractiveFormatting: true,
className: (0, clsx.default)(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
}, (0, _wordpress_block_editor.__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__ */ (0, react_jsx_runtime.jsx)(_wordpress_block_editor.BlockControls, {
group: "block",
children: isLinkTag && !lockUrlControls && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.ToolbarButton, {
name: "link",
icon: _wordpress_icons.link,
title: (0, _wordpress_i18n.__)("Link"),
shortcut: _wordpress_keycodes.displayShortcut.primary("k"),
onClick: () => setIsEditingURL(!isEditingURL),
isActive: isURLSet
})
}),
isLinkTag && isSelected && isEditingURL && !lockUrlControls && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.Popover, {
placement: "bottom",
onClose: () => {
setIsEditingURL(false);
richTextRef.current?.focus();
},
anchor: popoverAnchor,
focusOnMount: isEditingURL ? "firstElement" : false,
__unstableSlotName: "__unstable-block-tools-after",
shift: true,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_block_editor.LinkControl, {
value: linkValue,
onChange: setLink,
onRemove: () => {
unlink();
richTextRef.current?.focus();
},
forceIsEditingLink: !isURLSet,
settings: LINK_SETTINGS,
createSuggestion: createPageEntity && handleCreate,
withCreateSuggestion: userCanCreatePages,
createSuggestionButtonText: createButtonText
})
}),
hasContentControls && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_block_editor.InspectorControls, {
group: "content",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ContentControls, {
text,
url,
opensInNewTab,
isTextEditable: !lockTextControls,
isLinkEditable: isLinkTag && !lockUrlControls,
setText,
setLink,
unlink
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_block_editor.InspectorControls, {
group: "advanced",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(HTMLElementControl, {
tagName,
onChange: (value) => setAttributes({ tagName: value }),
options: [{
label: (0, _wordpress_i18n.__)("Default (<a>)"),
value: "a"
}, {
label: "<button>",
value: "button"
}]
}), isLinkTag && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.TextControl, {
label: (0, _wordpress_i18n.__)("Link relation"),
help: (0, _wordpress_element.createInterpolateElement)((0, _wordpress_i18n.__)("The <a>Link Relation</a> attribute defines the relationship between a linked resource and the current document."), { a: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Link, {
openInNewTab: true,
href: "https://developer.mozilla.org/docs/Web/HTML/Attributes/rel"
}) }),
value: rel || "",
onChange: (newRel) => setAttributes({ rel: newRel })
})]
})
] });
}
exports.default = ButtonEdit;
//# sourceMappingURL=edit.cjs.map