@wordpress/block-library
Version:
Block library for the WordPress editor.
254 lines (253 loc) • 10.7 kB
JavaScript
import clsx from "clsx";
import { Button, MenuGroup, MenuItem, ToolbarDropdownMenu } from "@wordpress/components";
import { BlockControls, InspectorControls, MediaPlaceholder, MediaReplaceFlow, store, useBlockEditingMode, useBlockProps, useInnerBlocksProps, useSettings } from "@wordpress/block-editor";
import { useMemo, useState } from "@wordpress/element";
import { __, _x, sprintf } from "@wordpress/i18n";
import { useDispatch, useSelect } from "@wordpress/data";
import { createBlock } from "@wordpress/blocks";
import { createBlobURL } from "@wordpress/blob";
import { store as store$1 } from "@wordpress/notices";
import { customLink, fullscreen, image, link, linkOff } from "@wordpress/icons";
import { sharedIcon } from "./shared-icon.mjs";
import { getImageAttributes, isGalleryFlexLayout } from "./shared.mjs";
import { getHrefAndDestination } from "./utils.mjs";
import { getDefaultLinkDestination } from "../image/utils.mjs";
import Gallery from "./gallery.mjs";
import { LINK_DESTINATION_ATTACHMENT, LINK_DESTINATION_LIGHTBOX, LINK_DESTINATION_MEDIA, LINK_DESTINATION_NONE } from "./constants.mjs";
import useGetMedia from "./use-get-media.mjs";
import useApplyGallerySettings from "./use-apply-gallery-settings.mjs";
import GalleryStyles from "./gallery-styles.mjs";
import GalleryControls from "./controls.mjs";
import useDynamicGallery from "./use-dynamic-gallery.mjs";
import { GalleryDynamicView, GallerySourcePanel } from "./dynamic-gallery.mjs";
import { ATTACHED_MEDIA, getDynamicSource } from "./dynamic-source.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/block-library/src/gallery/edit.jsx
const LINK_OPTIONS = [
{
icon: customLink,
label: __("Link images to attachment pages"),
value: LINK_DESTINATION_ATTACHMENT,
noticeText: __("Attachment Pages")
},
{
icon: image,
label: __("Link images to media files"),
value: LINK_DESTINATION_MEDIA,
noticeText: __("Media Files")
},
{
icon: fullscreen,
label: __("Enlarge on click"),
value: LINK_DESTINATION_LIGHTBOX,
noticeText: __("Lightbox effect"),
infoText: __("Scale images with a lightbox effect")
},
{
icon: linkOff,
label: _x("None", "Media item link option"),
value: LINK_DESTINATION_NONE,
noticeText: __("None")
}
];
const ALLOWED_MEDIA_TYPES = ["image"];
const PLACEHOLDER_TEXT = __("Drag and drop images, upload, or choose from your library.");
const DEFAULT_BLOCK = { name: "core/image" };
const EMPTY_ARRAY = [];
function GalleryEdit(props) {
const { setAttributes, attributes, className, clientId, insertBlocksAfter, context } = props;
const postId = context?.postId;
const postType = context?.postType;
const blockEditingMode = useBlockEditingMode();
const [lightboxSetting] = useSettings("blocks.core/image.lightbox");
const linkOptions = !lightboxSetting?.allowEditing ? LINK_OPTIONS.filter((option) => option.value !== LINK_DESTINATION_LIGHTBOX) : LINK_OPTIONS;
const { layout } = attributes;
const isDynamic = !!attributes.dynamicContent;
const linkTo = attributes.linkTo ?? (isDynamic ? LINK_DESTINATION_NONE : getDefaultLinkDestination());
const galleryAttributes = {
...attributes,
linkTo
};
const isFlexLayout = isGalleryFlexLayout(layout);
const { getBlocks } = useSelect(store);
const { replaceInnerBlocks, updateBlockAttributes, selectBlock } = useDispatch(store);
const { createSuccessNotice, createErrorNotice } = useDispatch(store$1);
const { innerBlockImages, multiGallerySelection, selectedStyleState } = useSelect((select) => {
const { getBlockName, getMultiSelectedBlockClientIds, getBlocks: _getBlocks, getSelectedBlockStyleState } = select(store);
const multiSelectedClientIds = getMultiSelectedBlockClientIds();
return {
innerBlockImages: _getBlocks(clientId),
multiGallerySelection: multiSelectedClientIds.length && multiSelectedClientIds.every((_clientId) => getBlockName(_clientId) === "core/gallery"),
selectedStyleState: getSelectedBlockStyleState(clientId)
};
}, [clientId]);
const isViewportStyleState = selectedStyleState?.viewport && selectedStyleState.viewport !== "default";
const imageData = useGetMedia(innerBlockImages);
const mediaById = useMemo(() => new Map(imageData.map((media) => [media.id, media])), [imageData]);
const hasImages = !!innerBlockImages.length;
const [appliedSort, setAppliedSort] = useState(null);
const dynamic = useDynamicGallery({
attributes: galleryAttributes,
setAttributes,
clientId,
postId,
postType
});
useApplyGallerySettings(innerBlockImages, mediaById, (imageAttributes) => getImageAttributes(galleryAttributes, imageAttributes, mediaById.get(imageAttributes.id)));
function isValidFileType(file) {
const mediaTypeSelector = file.type;
return ALLOWED_MEDIA_TYPES.some((mediaType) => mediaTypeSelector?.indexOf(mediaType) === 0) || file.blob;
}
function updateImages(selectedImages) {
const newFileUploads = Object.prototype.toString.call(selectedImages) === "[object FileList]";
const imageArray = Array.from(selectedImages, (file) => file.url || !newFileUploads && !isValidFileType(file) ? file : { blob: file.blob || createBlobURL(file) });
if (!imageArray.every(isValidFileType)) createErrorNotice(__("If uploading to a gallery all files need to be image formats"), {
id: "gallery-upload-invalid-file",
type: "snackbar"
});
const processedImages = imageArray.filter((file) => file.url || isValidFileType(file));
const newOrderMap = processedImages.reduce((result, image, index) => (result[image.id] = index, result), {});
const selectedIds = new Set(processedImages.map((img) => img.id));
const existingImageBlocks = !newFileUploads ? innerBlockImages.filter((block) => selectedIds.has(block.attributes.id)) : innerBlockImages;
const existingIds = new Set(existingImageBlocks.map((block) => block.attributes.id));
const newBlocks = processedImages.filter((img) => !existingIds.has(img.id)).map((image) => {
return createBlock("core/image", {
id: image.id,
blob: image.blob,
url: image.url,
caption: image.caption,
alt: image.alt
});
});
replaceInnerBlocks(clientId, existingImageBlocks.concat(newBlocks).sort((a, b) => newOrderMap[a.attributes.id] - newOrderMap[b.attributes.id]));
if (newBlocks?.length > 0) selectBlock(newBlocks[0].clientId);
}
function onUploadError(message) {
createErrorNotice(message, { type: "snackbar" });
}
function updateInnerImages(getAttributes) {
const images = getBlocks(clientId);
updateBlockAttributes(images.map((block) => block.clientId), Object.fromEntries(images.map((block) => [block.clientId, getAttributes(block, mediaById.get(block.attributes.id))])), { uniqueByBlock: true });
}
function setLinkTo(value) {
setAttributes({ linkTo: value });
updateInnerImages((block, media) => getHrefAndDestination(media, value, false, block.attributes, lightboxSetting));
const linkToText = [...linkOptions].find((linkType) => linkType.value === value);
createSuccessNotice(sprintf(__("All gallery image links updated to: %s"), linkToText.noticeText), {
id: "gallery-attributes-linkTo",
type: "snackbar"
});
}
const hasImageIds = hasImages && innerBlockImages.some((block) => !!block.attributes.id);
const mediaPlaceholderProps = {
addToGallery: false,
disableMediaButtons: innerBlockImages.some((block) => !block.attributes.id && block.attributes.url?.indexOf("blob:") === 0),
value: {}
};
const blockProps = useBlockProps({ className: clsx(className, "has-nested-images", `wp-block-gallery-${clientId}`) });
const innerBlocksProps = useInnerBlocksProps(blockProps, {
defaultBlock: DEFAULT_BLOCK,
directInsert: true,
orientation: "horizontal",
renderAppender: false,
allowedBlocks: isDynamic ? EMPTY_ARRAY : void 0
});
if (!hasImages && !isDynamic) return /* @__PURE__ */ jsxs("div", {
...innerBlocksProps,
children: [innerBlocksProps.children, /* @__PURE__ */ jsx(MediaPlaceholder, {
handleUpload: false,
icon: sharedIcon,
labels: {
title: __("Gallery"),
instructions: PLACEHOLDER_TEXT
},
onSelect: updateImages,
allowedTypes: ALLOWED_MEDIA_TYPES,
multiple: true,
onError: onUploadError,
...mediaPlaceholderProps,
children: blockEditingMode === "default" && /* @__PURE__ */ jsx(Button, {
__next40pxDefaultSize: true,
variant: "secondary",
onClick: dynamic.enableDynamicMode,
children: getDynamicSource(ATTACHED_MEDIA).title
})
})]
});
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsxs(InspectorControls, {
group: isViewportStyleState ? "style-state" : "default",
children: [!isViewportStyleState && /* @__PURE__ */ jsx(GallerySourcePanel, {
dynamic,
hasImages
}), /* @__PURE__ */ jsx(GalleryControls, {
attributes: galleryAttributes,
setAttributes,
clientId,
viewport: isViewportStyleState ? selectedStyleState.viewport : void 0,
innerBlockImages,
mediaById,
dynamic,
updateInnerImages,
appliedSort,
setAppliedSort
})]
}),
/* @__PURE__ */ jsx(BlockControls, {
group: "block",
children: /* @__PURE__ */ jsx(ToolbarDropdownMenu, {
icon: link,
label: __("Link"),
children: ({ onClose }) => /* @__PURE__ */ jsx(MenuGroup, { children: linkOptions.map((linkItem) => {
const isOptionSelected = linkTo === linkItem.value;
return /* @__PURE__ */ jsx(MenuItem, {
isSelected: isOptionSelected,
className: clsx("components-dropdown-menu__menu-item", { "is-active": isOptionSelected }),
iconPosition: "left",
icon: linkItem.icon,
onClick: () => {
setLinkTo(linkItem.value);
onClose();
},
role: "menuitemradio",
info: linkItem.infoText,
children: linkItem.label
}, linkItem.value);
}) })
})
}),
!multiGallerySelection && !isDynamic && /* @__PURE__ */ jsx(BlockControls, {
group: "other",
children: /* @__PURE__ */ jsx(MediaReplaceFlow, {
allowedTypes: ALLOWED_MEDIA_TYPES,
handleUpload: false,
onSelect: updateImages,
name: __("Add"),
multiple: true,
mediaIds: innerBlockImages.filter((block) => block.attributes.id).map((block) => block.attributes.id),
addToGallery: hasImageIds,
variant: "toolbar"
})
}),
/* @__PURE__ */ jsx(GalleryStyles, {
style: attributes.style,
clientId,
isFlexLayout
}),
isDynamic ? /* @__PURE__ */ jsx(GalleryDynamicView, {
...props,
dynamic,
blockProps,
innerBlocksProps,
multiGallerySelection
}) : /* @__PURE__ */ jsx(Gallery, {
...props,
blockProps: innerBlocksProps,
insertBlocksAfter,
multiGallerySelection,
children: innerBlocksProps.children
})
] });
}
export { GalleryEdit as default };
//# sourceMappingURL=edit.mjs.map