@wordpress/block-library
Version:
Block library for the WordPress editor.
765 lines (764 loc) • 29.8 kB
JavaScript
import clsx from "clsx";
import { CheckboxControl, DropdownMenu, ExternalLink, FocalPointPicker, MenuItem, Placeholder, Popover, ResizableBox, Spinner, TextControl, TextareaControl, ToolbarButton, ToolbarGroup, ToolbarItem, __experimentalToolsPanel, __experimentalToolsPanelItem, __experimentalUseCustomUnits } from "@wordpress/components";
import { useMergeRefs, useResizeObserver, useViewportMatch } from "@wordpress/compose";
import { useDispatch, useSelect } from "@wordpress/data";
import { BlockControls, BlockSettingsMenuControls, InspectorControls, MediaReplaceFlow, __experimentalGetShadowClassesAndStyles, __experimentalImageURLInputUI, __experimentalUseBorderProps, privateApis, store, useSettings } from "@wordpress/block-editor";
import { createInterpolateElement, useCallback, useEffect, useMemo, useRef, useState } from "@wordpress/element";
import { __, _x, isRTL, sprintf } from "@wordpress/i18n";
import { getFilename } from "@wordpress/url";
import { getBlockBindingsSource, switchToBlockType } from "@wordpress/blocks";
import { chevronDown, crop, overlayText, upload } from "@wordpress/icons";
import { store as store$1 } from "@wordpress/notices";
import { store as store$2 } from "@wordpress/core-data";
import { unlock } from "../lock-unlock.mjs";
import { createUpgradedEmbedBlock } from "../embed/util.mjs";
import { isExternalImage } from "./edit.mjs";
import { Caption } from "../utils/caption.mjs";
import { MediaControl } from "../utils/media-control.mjs";
import { useToolsPanelDropdownMenuProps } from "../utils/hooks.mjs";
import { getActiveDimensionValue, getDimensionResetAttributes, getDimensionUpdateAttributes, getStyleStateKey } from "../utils/style-state.mjs";
import { useOpenImageMediaEditorModal } from "./use-open-image-media-editor-modal.mjs";
import { ALLOWED_MEDIA_TYPES, DEFAULT_MEDIA_SIZE_SLUG, MIN_SIZE, SIZED_LAYOUTS } from "./constants.mjs";
import { evalAspectRatio, mediaPosition } from "./utils.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/block-library/src/image/image.jsx
const { DimensionsTool, ResolutionTool, mediaEditKey, mediaSideloadFromUrlKey } = unlock(privateApis);
const scaleOptions = [{
value: "cover",
label: _x("Cover", "Scale option for dimensions control"),
help: __("Image covers the space evenly.")
}, {
value: "contain",
label: _x("Contain", "Scale option for dimensions control"),
help: __("Image is contained without distortion.")
}];
const WRITEMODE_POPOVER_PROPS = { placement: "bottom-start" };
const ImageWrapper = ({ href, children }) => {
if (!href) return children;
return /* @__PURE__ */ jsx("a", {
href,
onClick: (event) => event.preventDefault(),
"aria-disabled": true,
style: {
pointerEvents: "none",
cursor: "default",
display: "inline"
},
children
});
};
function ContentOnlyControls({ attributes, setAttributes, lockAltControls, lockAltControlsMessage, lockTitleControls, lockTitleControlsMessage }) {
const [popoverAnchor, setPopoverAnchor] = useState(null);
const [isAltDialogOpen, setIsAltDialogOpen] = useState(false);
const [isTitleDialogOpen, setIsTitleDialogOpen] = useState(false);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(ToolbarItem, {
ref: setPopoverAnchor,
children: (toggleProps) => /* @__PURE__ */ jsx(DropdownMenu, {
icon: chevronDown,
label: __("More"),
toggleProps: {
...toggleProps,
description: __("Displays more controls.")
},
popoverProps: WRITEMODE_POPOVER_PROPS,
children: ({ onClose }) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(MenuItem, {
onClick: () => {
setIsAltDialogOpen(true);
onClose();
},
"aria-haspopup": "dialog",
children: _x("Alternative text", "Alternative text for an image. Block toolbar label, a low character count is preferred.")
}), /* @__PURE__ */ jsx(MenuItem, {
onClick: () => {
setIsTitleDialogOpen(true);
onClose();
},
"aria-haspopup": "dialog",
children: __("Title text")
})] })
})
}),
isAltDialogOpen && /* @__PURE__ */ jsx(Popover, {
placement: "bottom-start",
anchor: popoverAnchor,
onClose: () => setIsAltDialogOpen(false),
offset: 13,
variant: "toolbar",
children: /* @__PURE__ */ jsx("div", {
className: "wp-block-image__toolbar_content_textarea__container",
children: /* @__PURE__ */ jsx(TextareaControl, {
className: "wp-block-image__toolbar_content_textarea",
label: __("Alternative text"),
value: attributes.alt || "",
onChange: (value) => setAttributes({ alt: value }),
disabled: lockAltControls,
help: lockAltControls ? /* @__PURE__ */ jsx(Fragment, { children: lockAltControlsMessage }) : /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(ExternalLink, {
href: __("https://www.w3.org/WAI/tutorials/images/decision-tree/"),
children: __("Describe the purpose of the image.")
}),
/* @__PURE__ */ jsx("br", {}),
__("Leave empty if decorative.")
] })
})
})
}),
isTitleDialogOpen && /* @__PURE__ */ jsx(Popover, {
placement: "bottom-start",
anchor: popoverAnchor,
onClose: () => setIsTitleDialogOpen(false),
offset: 13,
variant: "toolbar",
children: /* @__PURE__ */ jsx("div", {
className: "wp-block-image__toolbar_content_textarea__container",
children: /* @__PURE__ */ jsx(TextControl, {
className: "wp-block-image__toolbar_content_textarea",
label: __("Title attribute"),
value: attributes.title || "",
onChange: (value) => setAttributes({ title: value }),
disabled: lockTitleControls,
help: lockTitleControls ? /* @__PURE__ */ jsx(Fragment, { children: lockTitleControlsMessage }) : createInterpolateElement(__("Describe the role of this image on the page. <a>(Note: many devices and browsers do not display this text.)</a>"), { a: /* @__PURE__ */ jsx(ExternalLink, { href: "https://www.w3.org/TR/html52/dom.html#the-title-attribute" }) })
})
})
})
] });
}
function Image({ temporaryURL, isSideloading, attributes, setAttributes, isSingleSelected, insertBlocksAfter, onReplace, onSelectImage, onSelectURL, onUploadError, context, clientId, blockEditingMode, parentLayoutType, maxContentWidth }) {
const { url = "", alt, align, id, href, rel, linkClass, linkDestination, title, width, height, aspectRatio, scale, focalPoint, linkTarget, sizeSlug, lightbox, metadata, isDecorative } = attributes;
const [imageElement, setImageElement] = useState();
const [resizeDelta, setResizeDelta] = useState(null);
const [pixelSize, setPixelSize] = useState({});
const [offsetTop, setOffsetTop] = useState(0);
const setResizeObserved = useResizeObserver(([entry]) => {
if (!resizeDelta) {
const [box] = entry.borderBoxSize;
setPixelSize({
width: box.inlineSize,
height: box.blockSize
});
}
setOffsetTop(entry.target.offsetTop);
});
const effectResizeableBoxPlacement = useCallback(() => {
setOffsetTop(imageElement?.offsetTop ?? 0);
}, [imageElement]);
const setRefs = useMergeRefs([setImageElement, setResizeObserved]);
const { allowResize = true, imageCrop = false } = context;
const isCroppedGalleryImage = imageCrop && parentLayoutType === "flex";
const { image, attachmentResolutionError } = useSelect((select) => {
return {
image: id && isSingleSelected ? select(store$2).getEntityRecord("postType", "attachment", id, { context: "view" }) : null,
attachmentResolutionError: id && isSingleSelected ? select(store$2).getResolutionError("getEntityRecord", [
"postType",
"attachment",
id,
{ context: "view" }
]) : null
};
}, [id, isSingleSelected]);
const { canInsertCover, imageEditing, imageSizes, maxWidth, editMediaEntity } = useSelect((select) => {
const { getBlockRootClientId, canInsertBlockType, getSettings } = select(store);
const rootClientId = getBlockRootClientId(clientId);
const settings = getSettings();
return {
imageEditing: settings.imageEditing,
imageSizes: settings.imageSizes,
maxWidth: settings.maxWidth,
editMediaEntity: settings?.[mediaEditKey],
canInsertCover: canInsertBlockType("core/cover", rootClientId)
};
}, [clientId]);
const { getBlock, getSettings } = useSelect(store);
const cropButtonRef = useRef();
const [pendingSwapUrl, setPendingSwapUrl] = useState();
const isSwappingMedia = !!pendingSwapUrl;
const handleMediaEditorModalClose = useCallback(() => cropButtonRef.current?.focus(), []);
const openImageMediaEditorModal = useOpenImageMediaEditorModal({
attributes,
setAttributes,
onClose: handleMediaEditorModalClose,
onUrlChange: setPendingSwapUrl
});
const { replaceBlocks, toggleSelection, __unstableMarkNextChangeAsNotPersistent } = useDispatch(store);
const { createErrorNotice, createSuccessNotice } = useDispatch(store$1);
const { editEntityRecord } = useDispatch(store$2);
const isLargeViewport = useViewportMatch("medium");
const isWideAligned = ["wide", "full"].includes(align);
const [{ loadedNaturalWidth, loadedNaturalHeight }, setLoadedNaturalSize] = useState({});
const [hasImageErrored, setHasImageErrored] = useState(false);
const hasNonContentControls = blockEditingMode === "default";
const isContentOnlyMode = blockEditingMode === "contentOnly";
const showDimensionsControls = allowResize && hasNonContentControls;
const isResizable = allowResize && hasNonContentControls && !isWideAligned && isLargeViewport;
const isUploading = !!temporaryURL || isSideloading;
const imageSizeOptions = imageSizes.filter(({ slug }) => image?.media_details?.sizes?.[slug]?.source_url).map(({ name, slug }) => ({
value: slug,
label: name
}));
useEffect(() => {
if (!id || !isSingleSelected) return;
if (attachmentResolutionError?.status === 404) {
__unstableMarkNextChangeAsNotPersistent();
setAttributes({ id: void 0 });
}
}, [
id,
isSingleSelected,
attachmentResolutionError,
setAttributes,
__unstableMarkNextChangeAsNotPersistent
]);
const canUploadExternalImage = isSingleSelected && isExternalImage(id, url) && !!getSettings()[mediaSideloadFromUrlKey];
const { naturalWidth, naturalHeight } = useMemo(() => {
return {
naturalWidth: imageElement?.naturalWidth || loadedNaturalWidth || void 0,
naturalHeight: imageElement?.naturalHeight || loadedNaturalHeight || void 0
};
}, [
loadedNaturalWidth,
loadedNaturalHeight,
imageElement?.complete
]);
useEffect(() => {
if (pendingSwapUrl && pendingSwapUrl === url && imageElement?.complete) setPendingSwapUrl(void 0);
}, [
pendingSwapUrl,
url,
imageElement
]);
function onImageError() {
setPendingSwapUrl(void 0);
setHasImageErrored(true);
const embedBlock = createUpgradedEmbedBlock({ attributes: { url } });
if (void 0 !== embedBlock && onReplace) onReplace(embedBlock);
}
function onImageLoad(event) {
setPendingSwapUrl(void 0);
setHasImageErrored(false);
setLoadedNaturalSize({
loadedNaturalWidth: event.target?.naturalWidth,
loadedNaturalHeight: event.target?.naturalHeight
});
}
function onSetHref(props) {
setAttributes(props);
}
function onSetLightbox(enable) {
if (enable && !lightboxSetting?.enabled) setAttributes({
lightbox: { enabled: true },
isDecorative: false
});
else if (!enable && lightboxSetting?.enabled) setAttributes({ lightbox: { enabled: false } });
else setAttributes({ lightbox: void 0 });
}
function resetLightbox() {
if (lightboxSetting?.enabled && lightboxSetting?.allowEditing) setAttributes({ lightbox: { enabled: false } });
else setAttributes({ lightbox: void 0 });
}
function onSetTitle(value) {
setAttributes({ title: value });
}
function updateAlt(newAlt) {
setAttributes({ alt: newAlt });
}
function updateIsDecorative(value) {
setAttributes({
isDecorative: value || void 0,
...value && {
alt: "",
caption: void 0,
href: void 0,
linkDestination: void 0,
linkTarget: void 0,
rel: void 0
}
});
}
const imperativeFocalPointPreview = (value) => {
if (imageElement) imageElement.style.setProperty("object-position", mediaPosition(value));
};
function updateImage(newSizeSlug) {
const newUrl = image?.media_details?.sizes?.[newSizeSlug]?.source_url;
if (!newUrl) return null;
setAttributes({
url: newUrl,
sizeSlug: newSizeSlug
});
}
function uploadExternal() {
const mediaSideloadFromUrl = getSettings()[mediaSideloadFromUrlKey];
if (!mediaSideloadFromUrl) return;
mediaSideloadFromUrl({
url,
onSuccess(img) {
onSelectImage(img);
createSuccessNotice(__("Image uploaded."), { type: "snackbar" });
},
onError(message) {
createErrorNotice(message, { type: "snackbar" });
}
});
}
const allowCrop = isSingleSelected && id && naturalWidth && naturalHeight && imageEditing && !!editMediaEntity && !!openImageMediaEditorModal && !isContentOnlyMode && !isUploading;
function switchToCover() {
replaceBlocks(clientId, switchToBlockType(getBlock(clientId), "core/cover"));
}
const dimensionsUnitsOptions = __experimentalUseCustomUnits({ availableUnits: ["px"] });
const [lightboxSetting] = useSettings("lightbox");
const showLightboxSetting = !!lightbox && lightbox?.enabled !== lightboxSetting?.enabled || lightboxSetting?.allowEditing;
const lightboxChecked = !!lightbox?.enabled || !lightbox && !!lightboxSetting?.enabled;
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const { selectedStyleState, hasSelectedStyleState } = useSelect((select) => {
if (!isSingleSelected) return {
selectedStyleState: void 0,
hasSelectedStyleState: false
};
const { getSelectedBlockStyleState, hasSelectedBlockStyleState } = select(store);
return {
selectedStyleState: getSelectedBlockStyleState(clientId),
hasSelectedStyleState: hasSelectedBlockStyleState(clientId)
};
}, [clientId, isSingleSelected]);
const selectedStyleStateKey = getStyleStateKey(selectedStyleState);
const activeWidth = getActiveDimensionValue({
attributes,
selectedState: selectedStyleState,
hasSelectedStyleState,
attributeKey: "width"
});
const activeHeight = getActiveDimensionValue({
attributes,
selectedState: selectedStyleState,
hasSelectedStyleState,
attributeKey: "height"
});
const activeAspectRatio = getActiveDimensionValue({
attributes,
selectedState: selectedStyleState,
hasSelectedStyleState,
attributeKey: "aspectRatio"
});
const activeScale = getActiveDimensionValue({
attributes,
selectedState: selectedStyleState,
hasSelectedStyleState,
attributeKey: "scale",
styleKey: "objectFit"
});
const setDimensionAttributes = (nextDimensions) => {
setAttributes(getDimensionUpdateAttributes({
style: attributes.style,
selectedState: selectedStyleState,
hasSelectedStyleState,
nextDimensions,
dimensionKeyMap: { scale: "objectFit" }
}));
};
const dimensionsControl = showDimensionsControls && (SIZED_LAYOUTS.includes(parentLayoutType) ? /* @__PURE__ */ jsx(DimensionsTool, {
panelId: clientId,
value: {
aspectRatio: activeAspectRatio,
scale: activeScale
},
onChange: ({ aspectRatio: newAspectRatio }) => {
setDimensionAttributes({
aspectRatio: newAspectRatio,
scale: "cover"
});
},
defaultAspectRatio: "auto",
tools: ["aspectRatio"]
}, selectedStyleStateKey) : /* @__PURE__ */ jsx(DimensionsTool, {
panelId: clientId,
value: {
width: activeWidth,
height: activeHeight,
scale: activeScale,
aspectRatio: activeAspectRatio
},
onChange: ({ width: newWidth, height: newHeight, scale: newScale, aspectRatio: newAspectRatio }) => {
setDimensionAttributes({
width: !newWidth && newHeight ? "auto" : newWidth,
height: newHeight,
aspectRatio: newAspectRatio,
scale: newScale
});
},
defaultScale: "cover",
defaultAspectRatio: "auto",
scaleOptions,
unitsOptions: dimensionsUnitsOptions,
tools: isWideAligned ? ["aspectRatio", "scale"] : [
"aspectRatio",
"widthHeight",
"scale"
]
}, selectedStyleStateKey));
const resetSettings = () => {
setAttributes({ lightbox: void 0 });
updateImage(DEFAULT_MEDIA_SIZE_SLUG);
};
const arePatternOverridesEnabled = metadata?.bindings?.__default?.source === "core/pattern-overrides";
const { lockUrlControls = false, lockHrefControls = false, lockAltControls = false, lockAltControlsMessage, lockTitleControls = false, lockTitleControlsMessage, hideCaptionControls = false } = useSelect((select) => {
if (!isSingleSelected) return {};
const { url: urlBinding, alt: altBinding, title: titleBinding, caption: captionBinding } = metadata?.bindings || {};
const hasParentPattern = !!context["pattern/overrides"];
const urlBindingSource = getBlockBindingsSource(urlBinding?.source);
const altBindingSource = getBlockBindingsSource(altBinding?.source);
const titleBindingSource = getBlockBindingsSource(titleBinding?.source);
return {
lockUrlControls: !!urlBinding && !urlBindingSource?.canUserEditValue?.({
select,
context,
args: urlBinding?.args
}),
lockHrefControls: hasParentPattern || arePatternOverridesEnabled,
hideCaptionControls: !!captionBinding,
lockAltControls: !!altBinding && !altBindingSource?.canUserEditValue?.({
select,
context,
args: altBinding?.args
}),
lockAltControlsMessage: altBindingSource?.label ? sprintf(__("Connected to %s"), altBindingSource.label) : __("Connected to dynamic data"),
lockTitleControls: !!titleBinding && !titleBindingSource?.canUserEditValue?.({
select,
context,
args: titleBinding?.args
}),
lockTitleControlsMessage: titleBindingSource?.label ? sprintf(__("Connected to %s"), titleBindingSource.label) : __("Connected to dynamic data")
};
}, [
arePatternOverridesEnabled,
context,
isSingleSelected,
metadata?.bindings
]);
const showUrlInput = isSingleSelected && !lockHrefControls && !lockUrlControls && !isDecorative;
const showCoverControls = isSingleSelected && canInsertCover && !isContentOnlyMode;
const showBlockControls = showUrlInput || allowCrop || showCoverControls;
const mediaControls = isSingleSelected && !lockUrlControls && /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(BlockControls, {
group: isContentOnlyMode ? "inline" : "other",
children: /* @__PURE__ */ jsx(MediaReplaceFlow, {
mediaId: id,
mediaURL: url,
allowedTypes: ALLOWED_MEDIA_TYPES,
onSelect: onSelectImage,
onSelectURL,
onError: onUploadError,
name: !url ? __("Add image") : __("Replace"),
onReset: () => onSelectImage(void 0),
variant: "toolbar"
})
}) });
const controls = /* @__PURE__ */ jsxs(Fragment, { children: [
showBlockControls && /* @__PURE__ */ jsxs(BlockControls, {
group: "block",
children: [
showUrlInput && /* @__PURE__ */ jsx(__experimentalImageURLInputUI, {
url: href || "",
onChangeUrl: onSetHref,
linkDestination,
mediaUrl: image && image.source_url || url,
mediaLink: image && image.link,
linkTarget,
linkClass,
rel,
showLightboxSetting,
lightboxEnabled: lightboxChecked,
onSetLightbox,
resetLightbox
}),
allowCrop && /* @__PURE__ */ jsx(ToolbarButton, {
ref: cropButtonRef,
onClick: openImageMediaEditorModal,
"aria-haspopup": "dialog",
icon: crop,
label: __("Edit image"),
disabled: isSwappingMedia
}),
showCoverControls && /* @__PURE__ */ jsx(ToolbarButton, {
icon: overlayText,
label: __("Add text over image"),
onClick: switchToCover
})
]
}),
canUploadExternalImage && /* @__PURE__ */ jsx(BlockControls, { children: /* @__PURE__ */ jsx(ToolbarGroup, { children: /* @__PURE__ */ jsx(ToolbarButton, {
onClick: uploadExternal,
icon: upload,
label: __("Upload to Media Library")
}) }) }),
isContentOnlyMode && /* @__PURE__ */ jsx(BlockControls, {
group: "block",
children: /* @__PURE__ */ jsx(ContentOnlyControls, {
attributes,
setAttributes,
lockAltControls,
lockAltControlsMessage,
lockTitleControls,
lockTitleControlsMessage
})
}),
isSingleSelected && /* @__PURE__ */ jsx(InspectorControls, {
group: "content",
children: /* @__PURE__ */ jsxs(__experimentalToolsPanel, {
label: __("Media"),
resetAll: () => {
onSelectImage(void 0);
setAttributes({ isDecorative: false });
},
dropdownMenuProps,
children: [
!lockUrlControls && /* @__PURE__ */ jsx(__experimentalToolsPanelItem, {
label: __("Image"),
hasValue: () => !!url,
onDeselect: () => onSelectImage(void 0),
isShownByDefault: true,
children: /* @__PURE__ */ jsx(MediaControl, {
mediaId: id,
mediaUrl: url,
alt,
filename: image?.media_details?.sizes?.full?.file || image?.slug || getFilename(url),
allowedTypes: ALLOWED_MEDIA_TYPES,
onSelect: onSelectImage,
onSelectURL,
onError: onUploadError,
onReset: () => onSelectImage(void 0),
isUploading,
emptyLabel: __("Add image")
})
}),
!isDecorative && /* @__PURE__ */ jsx(__experimentalToolsPanelItem, {
label: __("Alternative text"),
isShownByDefault: true,
hasValue: () => !!alt,
onDeselect: () => setAttributes({ alt: void 0 }),
children: /* @__PURE__ */ jsx(TextareaControl, {
label: __("Alternative text"),
value: alt || "",
onChange: updateAlt,
readOnly: lockAltControls,
help: lockAltControls ? /* @__PURE__ */ jsx(Fragment, { children: lockAltControlsMessage }) : /* @__PURE__ */ jsx(ExternalLink, {
href: __("https://www.w3.org/WAI/tutorials/images/decision-tree/"),
children: __("Describe the purpose of the image.")
})
})
}),
!lockAltControls && !lightboxChecked && /* @__PURE__ */ jsx(__experimentalToolsPanelItem, {
label: __("Mark as decorative"),
isShownByDefault: true,
hasValue: () => !!isDecorative,
onDeselect: () => setAttributes({ isDecorative: false }),
children: /* @__PURE__ */ jsx(CheckboxControl, {
label: __("Mark as decorative"),
checked: !!isDecorative,
onChange: updateIsDecorative,
help: __("Hidden from assistive technologies.")
})
})
]
})
}),
/* @__PURE__ */ jsxs(InspectorControls, {
group: "dimensions",
resetAllFilter: (attrs) => {
return getDimensionResetAttributes({
attributes: attrs,
selectedState: selectedStyleState,
hasSelectedStyleState,
keys: [
"aspectRatio",
"height",
"objectFit",
"width"
],
defaultAttributes: {
aspectRatio: void 0,
width: void 0,
height: void 0,
scale: void 0,
focalPoint: void 0
}
});
},
children: [dimensionsControl, !hasSelectedStyleState && url && scale && /* @__PURE__ */ jsx(__experimentalToolsPanelItem, {
label: __("Focal point"),
isShownByDefault: true,
hasValue: () => !!focalPoint,
onDeselect: () => setAttributes({ focalPoint: void 0 }),
panelId: clientId,
children: /* @__PURE__ */ jsx(FocalPointPicker, {
label: __("Focal point"),
url,
value: focalPoint,
onDragStart: imperativeFocalPointPreview,
onDrag: imperativeFocalPointPreview,
onChange: (newFocalPoint) => setAttributes({ focalPoint: newFocalPoint })
})
})]
}),
!!imageSizeOptions.length && /* @__PURE__ */ jsx(InspectorControls, { children: /* @__PURE__ */ jsx(__experimentalToolsPanel, {
label: __("Settings"),
resetAll: resetSettings,
dropdownMenuProps,
children: /* @__PURE__ */ jsx(ResolutionTool, {
value: sizeSlug,
defaultValue: DEFAULT_MEDIA_SIZE_SLUG,
onChange: updateImage,
options: imageSizeOptions
})
}) }),
/* @__PURE__ */ jsx(InspectorControls, {
group: "advanced",
children: /* @__PURE__ */ jsx(TextControl, {
label: __("Title attribute"),
value: title || "",
onChange: onSetTitle,
readOnly: lockTitleControls,
help: lockTitleControls ? /* @__PURE__ */ jsx(Fragment, { children: lockTitleControlsMessage }) : createInterpolateElement(__("Describe the role of this image on the page. <a>(Note: many devices and browsers do not display this text.)</a>"), { a: /* @__PURE__ */ jsx(ExternalLink, { href: "https://www.w3.org/TR/html52/dom.html#the-title-attribute" }) })
})
})
] });
const filename = getFilename(url);
let defaultedAlt;
if (isDecorative) defaultedAlt = filename ? sprintf(__("This image has been marked as decorative; its file name is %s"), filename) : __("This image has been marked as decorative.");
else if (alt) defaultedAlt = alt;
else if (filename) defaultedAlt = sprintf(__("This image has an empty alt attribute; its file name is %s"), filename);
else defaultedAlt = __("This image has an empty alt attribute");
const borderProps = __experimentalUseBorderProps(attributes);
const shadowProps = __experimentalGetShadowClassesAndStyles(attributes);
const { postType, postId, queryId } = context;
const isDescendentOfQueryLoop = Number.isFinite(queryId);
const img = /* @__PURE__ */ jsx(ImageWrapper, {
href,
children: temporaryURL && hasImageErrored ? /* @__PURE__ */ jsx(Placeholder, {
className: "wp-block-image__placeholder",
withIllustration: true,
children: /* @__PURE__ */ jsx(Spinner, {})
}) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("img", {
src: temporaryURL || url,
alt: defaultedAlt,
onError: onImageError,
onLoad: onImageLoad,
ref: setRefs,
className: clsx(borderProps.className, { "is-swapping-media": isSwappingMedia }),
width: naturalWidth,
height: naturalHeight,
style: {
aspectRatio,
...resizeDelta ? {
width: pixelSize.width + resizeDelta.width,
height: pixelSize.height + resizeDelta.height
} : (() => {
const style = {};
if (width === "auto") style.width = "auto";
else if (width !== void 0 && width !== null) style.width = typeof width === "number" ? `${width}px` : width;
if (height === "auto") style.height = "auto";
else if (height !== void 0 && height !== null) style.height = typeof height === "number" ? `${height}px` : height;
else if (!isCroppedGalleryImage) style.height = "auto";
return style;
})(),
objectFit: scale,
objectPosition: focalPoint && scale ? mediaPosition(focalPoint) : void 0,
...borderProps.style,
...shadowProps.style
}
}), (isUploading || isSwappingMedia) && /* @__PURE__ */ jsx(Spinner, {})] })
});
let resizableBox;
if (isResizable && isSingleSelected && !isUploading && !SIZED_LAYOUTS.includes(parentLayoutType)) {
const numericRatio = aspectRatio && evalAspectRatio(aspectRatio);
const customRatio = pixelSize.width / pixelSize.height;
const naturalRatio = naturalWidth / naturalHeight;
const ratio = numericRatio || customRatio || naturalRatio || 1;
const minWidth = naturalWidth < naturalHeight ? MIN_SIZE : MIN_SIZE * ratio;
const minHeight = naturalHeight < naturalWidth ? MIN_SIZE : MIN_SIZE / ratio;
const maxWidthBuffer = maxWidth * 2.5;
const maxResizeWidth = maxContentWidth || maxWidthBuffer;
let showRightHandle = false;
let showLeftHandle = false;
if (align === "center") {
showRightHandle = true;
showLeftHandle = true;
} else if (isRTL()) {
if (align === "left") showRightHandle = true;
else showLeftHandle = true;
} else if (align === "right") showLeftHandle = true;
else showRightHandle = true;
resizableBox = /* @__PURE__ */ jsx(ResizableBox, {
ref: effectResizeableBoxPlacement,
style: {
position: "absolute",
inset: `${offsetTop}px 0 0 0`
},
size: pixelSize,
minWidth,
maxWidth: maxResizeWidth,
minHeight,
maxHeight: maxResizeWidth / ratio,
lockAspectRatio: ratio,
enable: {
top: false,
right: showRightHandle,
bottom: true,
left: showLeftHandle
},
onResizeStart: () => {
toggleSelection(false);
},
onResize: (event, direction, elt, delta) => {
setResizeDelta(delta);
},
onResizeStop: (event, direction, elt, delta) => {
toggleSelection(true);
setResizeDelta(null);
setPixelSize((current) => ({
width: current.width + delta.width,
height: current.height + delta.height
}));
if (maxContentWidth && naturalWidth >= maxContentWidth && Math.abs(elt.offsetWidth - maxContentWidth) < 10) {
setAttributes({
width: void 0,
height: void 0
});
return;
}
setAttributes({
width: `${elt.offsetWidth}px`,
height: "auto",
aspectRatio: ratio === naturalRatio ? void 0 : String(ratio)
});
},
resizeRatio: align === "center" ? 2 : 1
});
}
if (!url && !temporaryURL) return /* @__PURE__ */ jsxs(Fragment, { children: [mediaControls, controls] });
/**
* Set the post's featured image with the current image.
*/
const setPostFeatureImage = () => {
editEntityRecord("postType", postType, postId, { featured_media: id });
createSuccessNotice(__("Post featured image updated."), { type: "snackbar" });
};
return /* @__PURE__ */ jsxs(Fragment, { children: [
mediaControls,
controls,
!isDescendentOfQueryLoop && postId && id ? /* @__PURE__ */ jsx(BlockSettingsMenuControls, { children: ({ canEdit, selectedClientIds }) => canEdit && selectedClientIds.length === 1 && clientId === selectedClientIds[0] && /* @__PURE__ */ jsx(MenuItem, {
onClick: setPostFeatureImage,
children: __("Set as featured image")
}) }) : null,
img,
resizableBox,
!isDecorative && /* @__PURE__ */ jsx(Caption, {
attributes,
setAttributes,
isSelected: isSingleSelected,
insertBlocksAfter,
label: __("Image caption text"),
showToolbarButton: isSingleSelected && (hasNonContentControls || isContentOnlyMode) && !hideCaptionControls
})
] });
}
export { Image as default };
//# sourceMappingURL=image.mjs.map