UNPKG

@wordpress/block-library

Version:
313 lines (312 loc) • 12.8 kB
"use strict"; 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_blob = require("@wordpress/blob"); let _wordpress_blocks = require("@wordpress/blocks"); let _wordpress_components = require("@wordpress/components"); let _wordpress_data = require("@wordpress/data"); let _wordpress_block_editor = require("@wordpress/block-editor"); let _wordpress_element = require("@wordpress/element"); let _wordpress_i18n = require("@wordpress/i18n"); let _wordpress_icons = require("@wordpress/icons"); let _wordpress_notices = require("@wordpress/notices"); let _wordpress_compose = require("@wordpress/compose"); let _wordpress_url = require("@wordpress/url"); let _wordpress_upload_media = require("@wordpress/upload-media"); let ___utils_hooks_js = require("../utils/hooks.cjs"); let __image_jsx = require("./image.cjs"); __image_jsx = __toESM(__image_jsx); let __utils_js = require("./utils.cjs"); let __use_max_width_observer_jsx = require("./use-max-width-observer.cjs"); let __constants_js = require("./constants.cjs"); let react_jsx_runtime = require("react/jsx-runtime"); // packages/block-library/src/image/edit.jsx const pickRelevantMediaFiles = (image, size) => { const imageProps = Object.fromEntries(Object.entries(image ?? {}).filter(([key]) => [ "alt", "id", "link", "caption" ].includes(key))); imageProps.url = image?.sizes?.[size]?.url || image?.media_details?.sizes?.[size]?.source_url || image.url; return imageProps; }; /** * Is the url for the image hosted externally. An externally hosted image has no * id and is not a blob url. * * @param {number=} id The id of the image. * @param {string=} url The url of the image. * * @return {boolean} Is the url an externally hosted url? */ const isExternalImage = (id, url) => url && !id && !(0, _wordpress_blob.isBlobURL)(url); /** * Checks if WP generated the specified image size. Size generation is skipped * when the image is smaller than the said size. * * @param {Object} image * @param {string} size * * @return {boolean} Whether or not it has default image size. */ function hasSize(image, size) { return "url" in (image?.sizes?.[size] ?? {}) || "source_url" in (image?.media_details?.sizes?.[size] ?? {}); } function ImageEdit({ attributes, setAttributes, isSelected: isSingleSelected, className, insertBlocksAfter, onReplace, context, clientId, __unstableParentLayout: parentLayout }) { const { url = "", id, width, height, sizeSlug, aspectRatio, scale, align, metadata } = attributes; const [temporaryURL, setTemporaryURL] = (0, _wordpress_element.useState)(attributes.blob); const containerRef = (0, _wordpress_element.useRef)(); const layoutType = parentLayout?.type || parentLayout?.default?.type; const isMaxWidthContainerWidth = !layoutType || layoutType !== "flex" && layoutType !== "grid"; const [maxWidthObserver, maxContentWidth] = (0, __use_max_width_observer_jsx.useMaxWidthObserver)(); const [placeholderResizeListener, { width: placeholderWidth }] = (0, _wordpress_compose.useResizeObserver)(); const isSmallContainer = placeholderWidth && placeholderWidth < 160; const { __unstableMarkNextChangeAsNotPersistent, replaceBlock } = (0, _wordpress_data.useDispatch)(_wordpress_block_editor.store); (0, _wordpress_element.useEffect)(() => { if (["wide", "full"].includes(align)) { __unstableMarkNextChangeAsNotPersistent(); setAttributes({ width: void 0, height: void 0 }); } }, [ __unstableMarkNextChangeAsNotPersistent, align, setAttributes ]); const { getSettings, getBlockRootClientId, getBlockName, canInsertBlockType } = (0, _wordpress_data.useSelect)(_wordpress_block_editor.store); const blockEditingMode = (0, _wordpress_block_editor.useBlockEditingMode)(); const { createErrorNotice } = (0, _wordpress_data.useDispatch)(_wordpress_notices.store); function onUploadError(message) { createErrorNotice(message, { type: "snackbar", explicitDismiss: true }); setTemporaryURL(); setAttributes({ blob: void 0 }); } function onFilesPreUpload(files) { if (files.length === 1) setTemporaryURL((0, _wordpress_blob.createBlobURL)(files[0])); } function onSelectImagesList(images) { const win = containerRef.current?.ownerDocument.defaultView; if (images.every((file) => file instanceof win.File)) { /** @type {File[]} */ const files = images; const rootClientId = getBlockRootClientId(clientId); if (files.some((file) => !(0, __utils_js.isValidFileType)(file))) createErrorNotice((0, _wordpress_i18n.__)("If uploading to a gallery all files need to be image formats"), { id: "gallery-upload-invalid-file", type: "snackbar" }); const imageBlocks = files.filter((file) => (0, __utils_js.isValidFileType)(file)).map((file) => (0, _wordpress_blocks.createBlock)("core/image", { blob: (0, _wordpress_blob.createBlobURL)(file) })); if (getBlockName(rootClientId) === "core/gallery") replaceBlock(clientId, imageBlocks); else if (canInsertBlockType("core/gallery", rootClientId)) { const galleryBlock = (0, _wordpress_blocks.createBlock)("core/gallery", {}, imageBlocks); replaceBlock(clientId, galleryBlock); } } } function onSelectImage(media) { if (Array.isArray(media)) { onSelectImagesList(media); return; } if (!media || !media.url) { setAttributes({ blob: void 0 }); setTemporaryURL(); return; } if ((0, _wordpress_blob.isBlobURL)(media.url)) { setTemporaryURL(media.url); return; } const { imageDefaultSize } = getSettings(); let newSize = __constants_js.DEFAULT_MEDIA_SIZE_SLUG; if (sizeSlug && hasSize(media, sizeSlug)) newSize = sizeSlug; else if (hasSize(media, imageDefaultSize)) newSize = imageDefaultSize; let mediaAttributes = pickRelevantMediaFiles(media, newSize); if (typeof mediaAttributes.caption === "string" && mediaAttributes.caption.includes("\n")) mediaAttributes.caption = mediaAttributes.caption.replace(/\n/g, "<br>"); if (!mediaAttributes.caption) { const { caption: omittedCaption, ...restMediaAttributes } = mediaAttributes; mediaAttributes = restMediaAttributes; } let additionalAttributes; if (!media.id || media.id !== id) additionalAttributes = { sizeSlug: newSize }; const linkDestination = attributes.linkDestination || (0, __utils_js.getDefaultLinkDestination)(); switch (linkDestination) { case __constants_js.LINK_DESTINATION_MEDIA: mediaAttributes.href = media.url; break; case __constants_js.LINK_DESTINATION_ATTACHMENT: mediaAttributes.href = media.link; break; case __constants_js.LINK_DESTINATION_NONE: mediaAttributes.href = void 0; } setAttributes({ blob: void 0, ...mediaAttributes, ...additionalAttributes, linkDestination }); setTemporaryURL(); } function onResetImage() { setAttributes({ url: void 0, alt: void 0, id: void 0, title: void 0, caption: void 0, blob: void 0 }); setTemporaryURL(); } function onSelectURL(newURL) { const normalizedNewURL = (0, _wordpress_url.getProtocol)(newURL) ? newURL : (0, _wordpress_url.prependHTTPS)(newURL); if (normalizedNewURL !== url) { setAttributes({ blob: void 0, url: normalizedNewURL, id: void 0, sizeSlug: getSettings().imageDefaultSize }); setTemporaryURL(); } } (0, ___utils_hooks_js.useUploadMediaFromBlobURL)({ url: temporaryURL, allowedTypes: __constants_js.ALLOWED_MEDIA_TYPES, onChange: onSelectImage, onError: onUploadError }); const src = isExternalImage(id, url) ? url : void 0; const isSideloading = (0, _wordpress_data.useSelect)((select) => { if (!window.__clientSideMediaProcessing || !id) return false; return select(_wordpress_upload_media.store).isUploadingById(id); }, [id]); const mediaPreview = !!url && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { alt: (0, _wordpress_i18n.__)("Edit image"), title: (0, _wordpress_i18n.__)("Edit image"), className: "edit-image-preview", src: url }); const borderProps = (0, _wordpress_block_editor.__experimentalUseBorderProps)(attributes); const shadowProps = (0, _wordpress_block_editor.__experimentalGetShadowClassesAndStyles)(attributes); const classes = (0, clsx.default)(className, { "is-transient": !!temporaryURL || isSideloading, "is-resized": !!width || !!height, [`size-${sizeSlug}`]: sizeSlug, "has-custom-border": !!borderProps.className || borderProps.style && Object.keys(borderProps.style).length > 0 }); const blockProps = (0, _wordpress_block_editor.useBlockProps)({ ref: containerRef, className: classes }); const { lockUrlControls = false, lockUrlControlsMessage } = (0, _wordpress_data.useSelect)((select) => { if (!isSingleSelected) return {}; const blockBindingsSource = (0, _wordpress_blocks.getBlockBindingsSource)(metadata?.bindings?.url?.source); return { lockUrlControls: !!metadata?.bindings?.url && !blockBindingsSource?.canUserEditValue?.({ select, context, args: metadata?.bindings?.url?.args }), lockUrlControlsMessage: blockBindingsSource?.label ? (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Connected to %s"), blockBindingsSource.label) : (0, _wordpress_i18n.__)("Connected to dynamic data") }; }, [ context, isSingleSelected, metadata?.bindings?.url ]); const pinnedHeight = height === "auto" ? void 0 : height; const placeholder = (content) => { return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_components.Placeholder, { className: (0, clsx.default)("block-editor-media-placeholder", { [borderProps.className]: !!borderProps.className && !isSingleSelected }), icon: !isSmallContainer && (lockUrlControls ? _wordpress_icons.plugins : _wordpress_icons.image), withIllustration: !isSingleSelected || isSmallContainer, label: !isSmallContainer && (0, _wordpress_i18n.__)("Image"), instructions: !lockUrlControls && !isSmallContainer && (0, _wordpress_i18n.__)("Drag and drop an image, upload, or choose from your library."), style: { aspectRatio: !(width && pinnedHeight) && aspectRatio ? aspectRatio : void 0, width: pinnedHeight && aspectRatio ? "100%" : width, height: width && aspectRatio ? "100%" : pinnedHeight, objectFit: scale, ...borderProps.style, ...shadowProps.style }, children: [ lockUrlControls && !isSmallContainer && lockUrlControlsMessage, !lockUrlControls && !isSmallContainer && content, placeholderResizeListener ] }); }; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("figure", { ...blockProps, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(__image_jsx.default, { temporaryURL, isSideloading, attributes, setAttributes, isSingleSelected, insertBlocksAfter, onReplace, onSelectImage, onSelectURL, onUploadError, onResetImage, context, clientId, blockEditingMode, parentLayoutType: layoutType, maxContentWidth }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_block_editor.MediaPlaceholder, { icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_block_editor.BlockIcon, { icon: _wordpress_icons.image }), onSelect: onSelectImage, onSelectURL, onFilesPreUpload, onError: onUploadError, placeholder, allowedTypes: __constants_js.ALLOWED_MEDIA_TYPES, handleUpload: (files) => files.length === 1, value: { id, src }, mediaPreview, disableMediaButtons: temporaryURL || url })] }), isSingleSelected && isMaxWidthContainerWidth && maxWidthObserver] }); } exports.ImageEdit = ImageEdit; exports.default = ImageEdit; exports.isExternalImage = isExternalImage; exports.pickRelevantMediaFiles = pickRelevantMediaFiles; //# sourceMappingURL=edit.cjs.map