UNPKG

@wordpress/block-library

Version:
54 lines (53 loc) • 2.1 kB
import { useEvent } from "@wordpress/compose"; import { useDispatch } from "@wordpress/data"; import { store } from "@wordpress/block-editor"; import { useEffect, useRef } from "@wordpress/element"; // packages/block-library/src/gallery/use-apply-gallery-settings.ts /** * Applies the gallery settings to images added to the gallery. * * An image block uploads its own file and sets its own size and link, so the * gallery settings can only be applied once the attachment loads. * * @param images The gallery's image blocks. * @param mediaById The loaded attachments, by id. * @param buildImageAttributes Returns the attributes to set on an image block. */ function useApplyGallerySettings(images, mediaById, buildImageAttributes) { const { __unstableMarkNextChangeAsNotPersistent, updateBlockAttributes } = useDispatch(store); const handledImagesRef = useRef(/* @__PURE__ */ new Set()); const applyGallerySettings = useEvent((blocks) => { const changedAttributes = Object.fromEntries(blocks.map((block) => [block.clientId, { ...buildImageAttributes(block.attributes), id: block.attributes.id, align: void 0 }])); __unstableMarkNextChangeAsNotPersistent(); updateBlockAttributes(blocks.map((block) => block.clientId), changedAttributes, { uniqueByBlock: true }); }); useEffect(() => { const handledImages = handledImagesRef.current; const clientIds = new Set(images.map((block) => block.clientId)); handledImages.forEach((clientId) => { if (!clientIds.has(clientId)) handledImages.delete(clientId); }); const newImages = []; images.forEach((block) => { if (handledImages.has(block.clientId)) return; if (block.originalContent) { handledImages.add(block.clientId); return; } if (!mediaById.has(block.attributes.id)) return; handledImages.add(block.clientId); newImages.push(block); }); if (newImages.length > 0) applyGallerySettings(newImages); }, [ images, mediaById, applyGallerySettings ]); } export { useApplyGallerySettings as default }; //# sourceMappingURL=use-apply-gallery-settings.mjs.map