UNPKG

@wordpress/block-library

Version:
103 lines (102 loc) 3.04 kB
// packages/block-library/src/utils/caption.js import clsx from "clsx"; import { useState, useEffect, useCallback } from "@wordpress/element"; import { usePrevious } from "@wordpress/compose"; import { __ } from "@wordpress/i18n"; import { BlockControls, __experimentalGetElementClassName, privateApis as blockEditorPrivateApis } from "@wordpress/block-editor"; import { ToolbarButton } from "@wordpress/components"; import { caption as captionIcon } from "@wordpress/icons"; import { createBlock, getDefaultBlockName } from "@wordpress/blocks"; import { unlock } from "../lock-unlock"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; function Caption({ attributeKey = "caption", attributes, setAttributes, isSelected, insertBlocksAfter, placeholder = __("Add caption"), label = __("Caption text"), showToolbarButton = true, excludeElementClassName, className, readOnly, tagName = "figcaption", addLabel = __("Add caption"), removeLabel = __("Remove caption"), icon = captionIcon, ...props }) { const caption = attributes[attributeKey]; const prevCaption = usePrevious(caption); const { PrivateRichText: RichText } = unlock(blockEditorPrivateApis); const isCaptionEmpty = RichText.isEmpty(caption); const isPrevCaptionEmpty = RichText.isEmpty(prevCaption); const [showCaption, setShowCaption] = useState(!isCaptionEmpty); useEffect(() => { if (!isCaptionEmpty && isPrevCaptionEmpty) { setShowCaption(true); } }, [isCaptionEmpty, isPrevCaptionEmpty]); useEffect(() => { if (!isSelected && isCaptionEmpty) { setShowCaption(false); } }, [isSelected, isCaptionEmpty]); const ref = useCallback( (node) => { if (node && isCaptionEmpty) { node.focus(); } }, [isCaptionEmpty] ); return /* @__PURE__ */ jsxs(Fragment, { children: [ showToolbarButton && /* @__PURE__ */ jsx(BlockControls, { group: "block", children: /* @__PURE__ */ jsx( ToolbarButton, { onClick: () => { setShowCaption(!showCaption); if (showCaption && caption) { setAttributes({ [attributeKey]: void 0 }); } }, icon, isPressed: showCaption, label: showCaption ? removeLabel : addLabel } ) }), showCaption && (!RichText.isEmpty(caption) || isSelected) && /* @__PURE__ */ jsx( RichText, { identifier: attributeKey, tagName, className: clsx( className, excludeElementClassName ? "" : __experimentalGetElementClassName("caption") ), ref, "aria-label": label, placeholder, value: caption, onChange: (value) => setAttributes({ [attributeKey]: value }), inlineToolbar: true, __unstableOnSplitAtEnd: () => insertBlocksAfter( createBlock(getDefaultBlockName()) ), readOnly, ...props } ) ] }); } export { Caption }; //# sourceMappingURL=caption.js.map