@wordpress/block-library
Version:
Block library for the WordPress editor.
499 lines (498 loc) • 20.1 kB
JavaScript
import clsx from "clsx";
import { store, useEntityProp } from "@wordpress/core-data";
import { useCallback, useEffect, useMemo, useRef, useState } from "@wordpress/element";
import { Placeholder, SandBox, Spinner } from "@wordpress/components";
import { compose, useEvent, useMergeRefs, useReducedMotion, useResizeObserver } from "@wordpress/compose";
import { ColorPalette, __experimentalUseGradient, privateApis, store as store$1, useBlockEditingMode, useBlockProps, useInnerBlocksProps, withColors } from "@wordpress/block-editor";
import { __ } from "@wordpress/i18n";
import { useDispatch, useRegistry, useSelect } from "@wordpress/data";
import { createBlocksFromInnerBlocksTemplate } from "@wordpress/blocks";
import { isBlobURL } from "@wordpress/blob";
import { store as store$2 } from "@wordpress/notices";
import { EMBED_VIDEO_BACKGROUND_TYPE, IMAGE_BACKGROUND_TYPE, VIDEO_BACKGROUND_TYPE, attributesFromMedia, dimRatioToClass, getPositionClassName, isContentPositionCenter, mediaPosition } from "../shared.mjs";
import CoverInspectorControls from "./inspector-controls.mjs";
import CoverBlockControls from "./block-controls.mjs";
import CoverPlaceholder from "./cover-placeholder.mjs";
import ResizableCoverPopover from "./resizable-cover-popover.mjs";
import { DEFAULT_BACKGROUND_COLOR, DEFAULT_OVERLAY_COLOR, compositeIsDark, getMediaColor } from "./color-utils.mjs";
import { DEFAULT_MEDIA_SIZE_SLUG } from "../constants.mjs";
import { getBackgroundEmbedHtml } from "../embed-video-utils.mjs";
import { unlock } from "../../lock-unlock.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/block-library/src/cover/edit/index.jsx
const { openMediaEditorModalKey } = unlock(privateApis);
function getInnerBlocksTemplate(attributes) {
return [["core/paragraph", {
style: { typography: { textAlign: "center" } },
placeholder: __("Write title…"),
...attributes
}]];
}
/**
* Is the URL a temporary blob URL? A blob URL is one that is used temporarily while
* the media (image or video) is being uploaded and will not have an id allocated yet.
*
* @param {number} id The id of the media.
* @param {string} url The url of the media.
*
* @return {boolean} Is the URL a Blob URL.
*/
const isTemporaryMedia = (id, url) => !id && isBlobURL(url);
function CoverEdit({ attributes, clientId, isSelected, overlayColor, setAttributes, setOverlayColor, toggleSelection, context: { postId, postType } }) {
const { contentPosition, id, url: originalUrl, backgroundType: originalBackgroundType, useFeaturedImage, dimRatio, focalPoint, hasParallax, isDark, isRepeated, minHeight, minHeightUnit, alt, allowedBlocks, templateLock, tagName: TagName = "div", isUserOverlayColor, sizeSlug, poster } = attributes;
const [featuredImage] = useEntityProp("postType", postType, "featured_media", postId);
const { getSettings } = useSelect(store$1);
const openMediaEditorModal = useSelect((select) => select(store$1).getSettings()[openMediaEditorModalKey], []);
const { __unstableMarkNextChangeAsNotPersistent, replaceInnerBlocks } = useDispatch(store$1);
const registry = useRegistry();
const getLatestProps = useEvent(() => ({
attributes,
overlayColor
}));
const { media } = useSelect((select) => {
return { media: featuredImage && useFeaturedImage ? select(store).getEntityRecord("postType", "attachment", featuredImage, { context: "view" }) : void 0 };
}, [featuredImage, useFeaturedImage]);
const mediaUrl = media?.media_details?.sizes?.[sizeSlug]?.source_url ?? media?.source_url;
useEffect(() => {
(async () => {
if (!useFeaturedImage) return;
const averageBackgroundColor = await getMediaColor(mediaUrl);
const { attributes: currentAttrs, overlayColor: currentOverlay } = getLatestProps();
let newOverlayColor = currentOverlay.color;
if (!currentAttrs.isUserOverlayColor) {
newOverlayColor = averageBackgroundColor;
__unstableMarkNextChangeAsNotPersistent();
setOverlayColor(newOverlayColor);
}
const newIsDark = compositeIsDark(currentAttrs.dimRatio, newOverlayColor, averageBackgroundColor);
__unstableMarkNextChangeAsNotPersistent();
setAttributes({
isDark: newIsDark,
isUserOverlayColor: currentAttrs.isUserOverlayColor || false
});
})();
}, [
mediaUrl,
__unstableMarkNextChangeAsNotPersistent,
setAttributes,
setOverlayColor,
useFeaturedImage,
getLatestProps
]);
const url = useFeaturedImage ? mediaUrl : originalUrl?.replaceAll("&", "&");
const backgroundType = useFeaturedImage ? IMAGE_BACKGROUND_TYPE : originalBackgroundType;
const { createErrorNotice } = useDispatch(store$2);
const { gradientClass, gradientValue } = __experimentalUseGradient();
const scaffoldInnerBlocks = () => {
const { getBlocks, isBlockSelected, getSelectedBlocksInitialCaretPosition } = registry.select(store$1);
if (getBlocks(clientId).length > 0) return;
const [fontSizes] = unlock(registry.select(store$1)).getBlockSettings(clientId, "typography.fontSizes");
const hasFontSizes = fontSizes?.length > 0;
replaceInnerBlocks(clientId, createBlocksFromInnerBlocksTemplate(getInnerBlocksTemplate({ fontSize: hasFontSizes ? "large" : void 0 })), isBlockSelected(clientId), getSelectedBlocksInitialCaretPosition());
};
const onSelectMedia = async (newMedia) => {
const mediaAttributes = attributesFromMedia(newMedia);
const isImage = [newMedia?.type, newMedia?.media_type].includes(IMAGE_BACKGROUND_TYPE);
const averageBackgroundColor = await getMediaColor(isImage ? newMedia?.url : void 0);
const { attributes: currentAttrs, overlayColor: currentOverlay } = getLatestProps();
let newOverlayColor = currentOverlay.color;
if (!currentAttrs.isUserOverlayColor) {
newOverlayColor = averageBackgroundColor;
setOverlayColor(newOverlayColor);
__unstableMarkNextChangeAsNotPersistent();
}
const newDimRatio = currentAttrs.url === void 0 && currentAttrs.dimRatio === 100 ? 50 : currentAttrs.dimRatio;
const newIsDark = compositeIsDark(newDimRatio, newOverlayColor, averageBackgroundColor);
if (backgroundType === IMAGE_BACKGROUND_TYPE && mediaAttributes?.id) {
const { imageDefaultSize } = getSettings();
if (sizeSlug && (newMedia?.sizes?.[sizeSlug] || newMedia?.media_details?.sizes?.[sizeSlug])) {
mediaAttributes.sizeSlug = sizeSlug;
mediaAttributes.url = newMedia?.sizes?.[sizeSlug]?.url || newMedia?.media_details?.sizes?.[sizeSlug]?.source_url;
} else if (newMedia?.sizes?.[imageDefaultSize] || newMedia?.media_details?.sizes?.[imageDefaultSize]) {
mediaAttributes.sizeSlug = imageDefaultSize;
mediaAttributes.url = newMedia?.sizes?.[imageDefaultSize]?.url || newMedia?.media_details?.sizes?.[imageDefaultSize]?.source_url;
} else mediaAttributes.sizeSlug = DEFAULT_MEDIA_SIZE_SLUG;
}
registry.batch(() => {
setAttributes({
...mediaAttributes,
focalPoint: void 0,
useFeaturedImage: void 0,
dimRatio: newDimRatio,
isDark: newIsDark,
isUserOverlayColor: currentAttrs.isUserOverlayColor || false
});
scaffoldInnerBlocks();
});
};
const onClearMedia = () => {
let newOverlayColor = overlayColor.color;
if (!isUserOverlayColor && overlayColor.color) {
newOverlayColor = DEFAULT_OVERLAY_COLOR;
setOverlayColor(void 0);
__unstableMarkNextChangeAsNotPersistent();
}
setAttributes({
url: void 0,
id: void 0,
backgroundType: void 0,
focalPoint: void 0,
hasParallax: void 0,
isRepeated: void 0,
useFeaturedImage: void 0,
isDark: compositeIsDark(dimRatio, newOverlayColor, DEFAULT_BACKGROUND_COLOR)
});
};
const onSetOverlayColor = async (newOverlayColor) => {
const averageBackgroundColor = await getMediaColor(url);
const { attributes: currentAttrs } = getLatestProps();
const newIsDark = compositeIsDark(currentAttrs.dimRatio, newOverlayColor, averageBackgroundColor);
setOverlayColor(newOverlayColor);
__unstableMarkNextChangeAsNotPersistent();
registry.batch(() => {
setAttributes({
isUserOverlayColor: true,
isDark: newIsDark
});
if (newOverlayColor) scaffoldInnerBlocks();
});
};
const onUpdateDimRatio = async (newDimRatio) => {
const averageBackgroundColor = await getMediaColor(url);
const { overlayColor: currentOverlay } = getLatestProps();
setAttributes({
dimRatio: newDimRatio,
isDark: compositeIsDark(newDimRatio, currentOverlay.color, averageBackgroundColor)
});
};
const onUploadError = (message) => {
createErrorNotice(message, { type: "snackbar" });
};
const onSelectEmbedUrl = (embedUrl) => {
setAttributes({
url: embedUrl,
backgroundType: EMBED_VIDEO_BACKGROUND_TYPE,
dimRatio: originalUrl === void 0 && dimRatio === 100 ? 50 : dimRatio,
id: void 0,
focalPoint: void 0,
hasParallax: void 0,
isRepeated: void 0,
useFeaturedImage: void 0
});
};
const { embedPreview, isFetchingEmbed } = useSelect((select) => {
if (backgroundType !== EMBED_VIDEO_BACKGROUND_TYPE || !url) return {
embedPreview: void 0,
isFetchingEmbed: false
};
const { getEmbedPreview, isRequestingEmbedPreview } = select(store);
return {
embedPreview: getEmbedPreview(url),
isFetchingEmbed: isRequestingEmbedPreview(url)
};
}, [url, backgroundType]);
const prefersReducedMotion = useReducedMotion();
const embedHtml = useMemo(() => {
if (backgroundType !== EMBED_VIDEO_BACKGROUND_TYPE || !embedPreview?.html) return null;
return getBackgroundEmbedHtml(embedPreview.html, { autoplay: !prefersReducedMotion });
}, [
embedPreview,
backgroundType,
prefersReducedMotion
]);
const [isSwappingMedia, setIsSwappingMedia] = useState(false);
const isUploadingMedia = isTemporaryMedia(id, url);
const isImageBackground = IMAGE_BACKGROUND_TYPE === backgroundType;
const isVideoBackground = VIDEO_BACKGROUND_TYPE === backgroundType;
const isEmbedVideoBackground = EMBED_VIDEO_BACKGROUND_TYPE === backgroundType;
const blockEditingMode = useBlockEditingMode();
const hasNonContentControls = blockEditingMode === "default";
const [resizeListener, { height, width }] = useResizeObserver();
const resizableBoxDimensions = useMemo(() => {
return {
height: minHeightUnit === "px" && minHeight ? minHeight : "auto",
width: "auto"
};
}, [minHeight, minHeightUnit]);
const minHeightWithUnit = minHeight && minHeightUnit ? `${minHeight}${minHeightUnit}` : minHeight;
const isImgElement = !(hasParallax || isRepeated);
const style = { minHeight: minHeightWithUnit || void 0 };
const backgroundImage = url ? `url(${url})` : void 0;
const backgroundPosition = mediaPosition(focalPoint);
const bgStyle = { backgroundColor: overlayColor.color };
const mediaStyle = { objectPosition: focalPoint && isImgElement ? mediaPosition(focalPoint) : void 0 };
const hasBackground = !!(url || overlayColor.color || gradientValue);
const hasInnerBlocks = useSelect((select) => select(store$1).getBlock(clientId).innerBlocks.length > 0, [clientId]);
const ref = useRef();
const [dropZoneElement, setDropZoneElement] = useState(null);
const blockProps = useBlockProps({ ref: useMergeRefs([ref, setDropZoneElement]) });
const innerBlocksProps = useInnerBlocksProps({ className: "wp-block-cover__inner-container" }, {
allowedBlocks,
templateLock,
dropZoneElement
});
const mediaElement = useRef();
const editMediaButtonRef = useRef();
useEffect(() => {
if (prefersReducedMotion && isVideoBackground) mediaElement.current?.pause();
}, [prefersReducedMotion, isVideoBackground]);
const currentSettings = {
isVideoBackground,
isImageBackground,
mediaElement,
hasInnerBlocks,
url,
isImgElement,
overlayColor
};
const openCoverMediaEditorModal = useCallback(() => {
if (!id || !openMediaEditorModal) return;
const previousImage = {
id,
url: getLatestProps().attributes.url
};
let isUndone = false;
openMediaEditorModal({
id,
onClose: () => {
editMediaButtonRef.current?.focus();
},
onUndo: () => {
isUndone = true;
setIsSwappingMedia(false);
setAttributes(previousImage);
},
onUpdate: async ({ id: newId, url: newUrl }) => {
if (typeof newId !== "number") return;
if (newId !== id && newUrl) setIsSwappingMedia(true);
const nextAttributes = {
id: newId,
backgroundType: IMAGE_BACKGROUND_TYPE,
...newUrl ? { url: newUrl } : {},
...newId !== id ? { sizeSlug: DEFAULT_MEDIA_SIZE_SLUG } : {}
};
if (newUrl) {
const averageBackgroundColor = await getMediaColor(newUrl);
if (isUndone) return;
const { attributes: currentAttrs, overlayColor: currentOverlay } = getLatestProps();
let newOverlayColor = currentOverlay.color;
if (!currentAttrs.isUserOverlayColor) {
newOverlayColor = averageBackgroundColor;
setOverlayColor(newOverlayColor);
__unstableMarkNextChangeAsNotPersistent();
}
nextAttributes.isDark = compositeIsDark(currentAttrs.dimRatio, newOverlayColor, averageBackgroundColor);
nextAttributes.isUserOverlayColor = currentAttrs.isUserOverlayColor || false;
}
setAttributes(nextAttributes);
const { hasParallax: currentHasParallax, isRepeated: currentIsRepeated } = getLatestProps().attributes;
if (currentHasParallax || currentIsRepeated) setIsSwappingMedia(false);
}
});
}, [
id,
getLatestProps,
openMediaEditorModal,
setAttributes,
setOverlayColor,
__unstableMarkNextChangeAsNotPersistent
]);
const showEditMediaButton = hasNonContentControls && !useFeaturedImage && isImageBackground && !!id && !!url && !isUploadingMedia && !!openMediaEditorModal;
const toggleUseFeaturedImage = async () => {
const newUseFeaturedImage = !useFeaturedImage;
const averageBackgroundColor = newUseFeaturedImage ? await getMediaColor(mediaUrl) : DEFAULT_BACKGROUND_COLOR;
const { attributes: currentAttrs, overlayColor: currentOverlay } = getLatestProps();
const newOverlayColor = !currentAttrs.isUserOverlayColor ? averageBackgroundColor : currentOverlay.color;
if (!currentAttrs.isUserOverlayColor) {
if (newUseFeaturedImage) setOverlayColor(newOverlayColor);
else setOverlayColor(void 0);
__unstableMarkNextChangeAsNotPersistent();
}
const newDimRatio = currentAttrs.dimRatio === 100 ? 50 : currentAttrs.dimRatio;
const newIsDark = compositeIsDark(newDimRatio, newOverlayColor, averageBackgroundColor);
registry.batch(() => {
setAttributes({
id: void 0,
url: void 0,
useFeaturedImage: newUseFeaturedImage,
dimRatio: newDimRatio,
backgroundType: useFeaturedImage ? IMAGE_BACKGROUND_TYPE : void 0,
isDark: newIsDark
});
if (newUseFeaturedImage) scaffoldInnerBlocks();
});
};
const blockControls = /* @__PURE__ */ jsx(CoverBlockControls, {
attributes,
setAttributes,
onSelectMedia,
onSelectEmbedUrl,
currentSettings,
toggleUseFeaturedImage,
onClearMedia,
blockEditingMode,
onEditMedia: openCoverMediaEditorModal,
editMediaButtonRef,
showEditMediaButton,
isEditMediaDisabled: isSwappingMedia
});
const inspectorControls = /* @__PURE__ */ jsx(CoverInspectorControls, {
attributes,
setAttributes,
clientId,
setOverlayColor: onSetOverlayColor,
coverRef: ref,
currentSettings,
onSelectMedia,
onUploadError,
toggleUseFeaturedImage,
updateDimRatio: onUpdateDimRatio,
onClearMedia,
featuredImage: media,
isSelected
});
const resizableCoverProps = {
className: "block-library-cover__resize-container",
clientId,
height,
minHeight: minHeightWithUnit,
onResizeStart: () => {
setAttributes({ minHeightUnit: "px" });
toggleSelection(false);
},
onResize: (value) => {
setAttributes({ minHeight: value });
},
onResizeStop: (newMinHeight) => {
toggleSelection(true);
setAttributes({ minHeight: newMinHeight });
},
showHandle: !attributes.style?.dimensions?.aspectRatio,
size: resizableBoxDimensions,
width
};
if (!useFeaturedImage && !hasInnerBlocks && !hasBackground) return /* @__PURE__ */ jsxs(Fragment, { children: [
blockControls,
inspectorControls,
hasNonContentControls && isSelected && /* @__PURE__ */ jsx(ResizableCoverPopover, { ...resizableCoverProps }),
/* @__PURE__ */ jsxs(TagName, {
...blockProps,
className: clsx("is-placeholder", blockProps.className),
style: {
...blockProps.style,
minHeight: minHeightWithUnit || void 0
},
children: [resizeListener, /* @__PURE__ */ jsx(CoverPlaceholder, {
onSelectMedia,
onError: onUploadError,
toggleUseFeaturedImage,
children: /* @__PURE__ */ jsx("div", {
className: "wp-block-cover__placeholder-background-options",
children: /* @__PURE__ */ jsx(ColorPalette, {
disableCustomColors: true,
value: overlayColor.color,
onChange: onSetOverlayColor,
clearable: false,
presentation: "toggle-buttons",
"aria-label": __("Overlay color")
})
})
})]
})
] });
const classes = clsx({
"is-dark-theme": isDark,
"is-light": !isDark,
"is-transient": isUploadingMedia || isSwappingMedia,
"has-parallax": hasParallax,
"is-repeated": isRepeated,
"has-custom-content-position": !isContentPositionCenter(contentPosition)
}, getPositionClassName(contentPosition));
const showOverlay = url || !useFeaturedImage || useFeaturedImage && !url;
return /* @__PURE__ */ jsxs(Fragment, { children: [
blockControls,
inspectorControls,
/* @__PURE__ */ jsxs(TagName, {
...blockProps,
className: clsx(classes, blockProps.className),
style: {
...style,
...blockProps.style
},
"data-url": url,
children: [
resizeListener,
!url && useFeaturedImage && /* @__PURE__ */ jsx(Placeholder, {
className: "wp-block-cover__image--placeholder-image",
withIllustration: true
}),
url && isImageBackground && (isImgElement ? /* @__PURE__ */ jsx("img", {
ref: mediaElement,
className: "wp-block-cover__image-background",
alt,
src: url,
style: mediaStyle,
onLoad: () => setIsSwappingMedia(false),
onError: () => setIsSwappingMedia(false)
}) : /* @__PURE__ */ jsx("div", {
ref: mediaElement,
role: alt ? "img" : void 0,
"aria-label": alt ? alt : void 0,
className: clsx(classes, "wp-block-cover__image-background"),
style: {
backgroundImage,
backgroundPosition
}
})),
url && isVideoBackground && /* @__PURE__ */ jsx("video", {
ref: mediaElement,
className: "wp-block-cover__video-background",
autoPlay: !prefersReducedMotion,
muted: true,
loop: true,
src: url,
poster,
style: mediaStyle
}),
isEmbedVideoBackground && embedHtml && /* @__PURE__ */ jsx("div", {
ref: mediaElement,
className: "wp-block-cover__video-background wp-block-cover__embed-background",
style: mediaStyle,
children: /* @__PURE__ */ jsx(SandBox, {
allowSameOrigin: true,
html: embedHtml,
title: "Background video",
styles: ["iframe{position:fixed;top:0;left:0;width:100%;height:100%;}"]
})
}),
isEmbedVideoBackground && !embedHtml && isFetchingEmbed && /* @__PURE__ */ jsx(Spinner, {}),
showOverlay && /* @__PURE__ */ jsx("span", {
"aria-hidden": "true",
className: clsx("wp-block-cover__background", dimRatioToClass(dimRatio), {
[overlayColor.class]: overlayColor.class,
"has-background-dim": dimRatio !== void 0,
"wp-block-cover__gradient-background": url && gradientValue && dimRatio !== 0,
"has-background-gradient": gradientValue,
[gradientClass]: gradientClass
}),
style: {
backgroundImage: gradientValue,
...bgStyle
}
}),
(isUploadingMedia || isSwappingMedia) && /* @__PURE__ */ jsx(Spinner, {}),
/* @__PURE__ */ jsx(CoverPlaceholder, {
disableMediaButtons: true,
onSelectMedia,
onError: onUploadError,
toggleUseFeaturedImage
}),
/* @__PURE__ */ jsx("div", { ...innerBlocksProps })
]
}),
hasNonContentControls && isSelected && /* @__PURE__ */ jsx(ResizableCoverPopover, { ...resizableCoverProps })
] });
}
var edit_default = compose([withColors({ overlayColor: "background-color" })])(CoverEdit);
export { edit_default as default };
//# sourceMappingURL=index.mjs.map