@wordpress/block-library
Version:
Block library for the WordPress editor.
168 lines (167 loc) • 6.82 kB
JavaScript
import { useMemo } from "@wordpress/element";
import { useDispatch, useRegistry, useSelect } from "@wordpress/data";
import { store } from "@wordpress/block-editor";
import { store as store$1 } from "@wordpress/core-data";
import { createBlock } from "@wordpress/blocks";
import { pickRelevantMediaFiles } from "./shared.mjs";
import { getHrefAndDestination } from "./utils.mjs";
import { getUpdatedLinkTargetSettings } from "../image/utils.mjs";
import { ATTACHED_MEDIA, DEFAULT_ORDER, DEFAULT_ORDERBY, MAX_IMAGES, getDynamicSource, getSourceQuery } from "./dynamic-source.mjs";
// packages/block-library/src/gallery/use-dynamic-gallery.js
const EMPTY_ARRAY = [];
/**
* Builds the attributes for a `core/image` block from a media (attachment)
* record, applying the gallery-wide settings that affect how the image renders.
*
* Used to construct the (non-persisted) image blocks previewed in dynamic mode,
* and the real image blocks created when a dynamic gallery is converted
* ("pinned") back to individual images. The frontend equivalent is
* `block_core_gallery_render_dynamic_image()` in `index.php`.
*
* @param {Object} media A media object as returned by the REST API.
* @param {Object} galleryAttributes The gallery block's attributes.
* @return {Object} Attributes to pass to `createBlock( 'core/image', ... )`.
*/
function buildImageBlockAttributes(media, galleryAttributes) {
const { sizeSlug, linkTo, linkTarget, aspectRatio } = galleryAttributes;
const hasAspectRatio = !!aspectRatio && aspectRatio !== "auto";
return {
id: media.id,
...pickRelevantMediaFiles(media, sizeSlug),
...getHrefAndDestination(media, linkTo),
...getUpdatedLinkTargetSettings(linkTarget, galleryAttributes),
sizeSlug,
caption: media.caption?.raw || "",
alt: media.alt_text || "",
aspectRatio: hasAspectRatio ? aspectRatio : void 0,
scale: hasAspectRatio ? "cover" : void 0
};
}
/**
* Builds a set of `core/image` blocks from the resolved media, applying the
* gallery-wide settings. Each call mints fresh client IDs, so it can produce
* both the editor preview and the materialized inner blocks on convert.
*
* @param {Object[]} media Media records from the REST API.
* @param {Object} galleryAttributes The image-relevant gallery attributes.
* @return {Object[]} New `core/image` block instances.
*/
function buildImageBlocks(media, galleryAttributes) {
return media.map((mediaItem) => createBlock("core/image", buildImageBlockAttributes(mediaItem, galleryAttributes)));
}
/**
* Bundles the Gallery block's "dynamic mode" source resolution and actions.
*
* Dynamic mode resolves the gallery's images from a configured source
* (`attributes.dynamicContent`) instead of from manually-added inner image
* blocks. This hook centralizes the shared, single-instance pieces — the source
* resolution (one `getEntityRecords`), the editor-preview blocks, and the
* mode/ordering actions — out of the block's `edit` component. Transient UI
* concerns (e.g. the convert-to-dynamic confirmation) live in the components
* that own them.
*
* @param {Object} options
* @param {Object} options.attributes The gallery block attributes.
* @param {Function} options.setAttributes The block's `setAttributes`.
* @param {string} options.clientId The block client ID.
* @param {?number} options.postId The current post ID (from block context).
* @param {?string} options.postType The current post type (from block context).
* @return {Object} Dynamic-mode source data and actions.
*/
function useDynamicGallery({ attributes, setAttributes, clientId, postId, postType }) {
const { dynamicContent } = attributes;
const canUseDynamicSource = !!postType;
const sourceDescriptor = getDynamicSource(dynamicContent?.source);
const sourceOrderby = dynamicContent?.args?.orderBy ?? DEFAULT_ORDERBY;
const sourceOrder = dynamicContent?.args?.order ?? DEFAULT_ORDER;
const registry = useRegistry();
const { replaceInnerBlocks, __unstableMarkNextChangeAsNotPersistent } = useDispatch(store);
const query = useMemo(() => dynamicContent ? getSourceQuery(dynamicContent, { postId }) : null, [dynamicContent, postId]);
const { dynamicMedia, dynamicMediaTotal, isResolvingDynamic } = useSelect((select) => {
if (!query) return {
dynamicMedia: EMPTY_ARRAY,
dynamicMediaTotal: 0,
isResolvingDynamic: false
};
const selectorArgs = [
"postType",
"attachment",
query
];
return {
dynamicMedia: select(store$1).getEntityRecords(...selectorArgs) ?? EMPTY_ARRAY,
dynamicMediaTotal: select(store$1).getEntityRecordsTotalItems(...selectorArgs) ?? 0,
isResolvingDynamic: !select(store$1).hasFinishedResolution("getEntityRecords", selectorArgs)
};
}, [query]);
const hasMoreImagesThanCap = dynamicMediaTotal > MAX_IMAGES;
const { sizeSlug, linkTo, linkTarget, aspectRatio } = attributes;
const imageAttributes = useMemo(() => ({
sizeSlug,
linkTo,
linkTarget,
aspectRatio
}), [
sizeSlug,
linkTo,
linkTarget,
aspectRatio
]);
const dynamicImageBlocks = useMemo(() => buildImageBlocks(dynamicMedia, imageAttributes), [dynamicMedia, imageAttributes]);
const galleryContext = useMemo(() => ({
allowResize: attributes.allowResize ?? false,
imageCrop: attributes.imageCrop,
fixedHeight: attributes.fixedHeight,
navigationButtonType: attributes.navigationButtonType
}), [
attributes.allowResize,
attributes.imageCrop,
attributes.fixedHeight,
attributes.navigationButtonType
]);
function enableDynamicMode() {
registry.batch(() => {
setAttributes({ dynamicContent: { source: ATTACHED_MEDIA } });
__unstableMarkNextChangeAsNotPersistent();
replaceInnerBlocks(clientId, []);
});
}
function convertToStatic() {
registry.batch(() => {
replaceInnerBlocks(clientId, buildImageBlocks(dynamicMedia, imageAttributes));
__unstableMarkNextChangeAsNotPersistent();
setAttributes({ dynamicContent: void 0 });
});
}
function setSourceOrder(nextOrderby, nextOrder) {
const nextArgs = { ...dynamicContent?.args };
delete nextArgs.orderBy;
delete nextArgs.order;
if (nextOrderby !== void 0 && (nextOrderby !== DEFAULT_ORDERBY || nextOrder !== DEFAULT_ORDER)) {
nextArgs.orderBy = nextOrderby;
nextArgs.order = nextOrder;
}
const nextSource = { ...dynamicContent };
if (Object.keys(nextArgs).length) nextSource.args = nextArgs;
else delete nextSource.args;
setAttributes({ dynamicContent: nextSource });
}
return {
dynamicContent,
canUseDynamicSource,
sourceDescriptor,
hasMoreImagesThanCap,
dynamicMediaTotal,
sourceOrderby,
sourceOrder,
dynamicMedia,
dynamicImageBlocks,
isResolvingDynamic,
galleryContext,
enableDynamicMode,
convertToStatic,
setSourceOrder
};
}
export { useDynamicGallery as default };
//# sourceMappingURL=use-dynamic-gallery.mjs.map