UNPKG

@wordpress/block-library

Version:
261 lines (260 loc) • 11.4 kB
import { store } from "@wordpress/core-data"; import { privateApis, store as store$1 } from "@wordpress/block-editor"; import { __unstableStripHTML } from "@wordpress/dom"; import { useRegistry, useSelect } from "@wordpress/data"; import { useCallback, useEffect, useRef } from "@wordpress/element"; import { unlock } from "../lock-unlock.mjs"; import { DEFAULT_MEDIA_SIZE_SLUG, LINK_DESTINATION_ATTACHMENT, LINK_DESTINATION_MEDIA } from "./constants.mjs"; // packages/block-library/src/image/use-open-image-media-editor-modal.js function normalizeImageBlockCaption(caption) { if (typeof caption !== "string") return ""; if (!__unstableStripHTML(caption).trim()) return ""; return caption.replace(/\n/g, "<br>"); } function getAttachmentCaption(attachment) { const caption = attachment?.caption; if (typeof caption === "string") return normalizeImageBlockCaption(caption); if (caption && typeof caption === "object" && Object.hasOwn(caption, "raw")) return normalizeImageBlockCaption(caption.raw); } function getImageBlockMetadataFromAttachment(attachment) { return { alt: typeof attachment?.alt_text === "string" ? attachment.alt_text : attachment?.alt || "", caption: getAttachmentCaption(attachment) }; } function normalizeMetadataAttribute(value) { return value || ""; } function getSyncedImageBlockAttributes(currentAttributes, originalAttachment, updatedAttachment) { if (!originalAttachment || !updatedAttachment) return {}; const originalMetadata = getImageBlockMetadataFromAttachment(originalAttachment); const updatedMetadata = getImageBlockMetadataFromAttachment(updatedAttachment); const syncedAttributes = {}; const normalizedCurrentAlt = normalizeMetadataAttribute(currentAttributes.alt); if (originalMetadata.alt !== updatedMetadata.alt && (normalizedCurrentAlt === originalMetadata.alt || !normalizedCurrentAlt)) syncedAttributes.alt = updatedMetadata.alt; const normalizedCurrentCaption = normalizeMetadataAttribute(currentAttributes.caption); if (originalMetadata.caption !== void 0 && updatedMetadata.caption !== void 0 && originalMetadata.caption !== updatedMetadata.caption && (normalizedCurrentCaption === originalMetadata.caption || !normalizedCurrentCaption)) syncedAttributes.caption = updatedMetadata.caption || void 0; return syncedAttributes; } /** * Resolves the attributes needed to keep the selected image size on a new * attachment. * * WordPress skips generating a sub-size larger than the file itself, so the * selected size may not exist on the edited image; fall back to full when it * doesn't. * * @param {string|undefined} sizeSlug The block's currently selected size. * @param {Object} attachment The new attachment record. * * @return {Object|undefined} Attributes to apply, if any. */ function getNewAttachmentSizeAttributes(sizeSlug, attachment) { const sizes = attachment.media_details?.sizes; if (!sizeSlug || sizeSlug === DEFAULT_MEDIA_SIZE_SLUG || !sizes) return; const sizeUrl = sizes[sizeSlug]?.source_url; if (sizeUrl) return { url: sizeUrl }; const fullUrl = attachment.source_url ?? sizes.full?.source_url; return fullUrl ? { url: fullUrl, sizeSlug: DEFAULT_MEDIA_SIZE_SLUG } : void 0; } /** * Resolves the link attributes needed to keep the block's link pointing at the * new attachment. * * Only the destinations derived from the attachment follow the edited image. A * `custom` link is the user's own URL and a `none` link has nothing to point * at, so both are left alone. When the record doesn't carry the field, the * existing link is kept rather than cleared. * * @param {string|undefined} linkDestination The block's link destination. * @param {Object} attachment The new attachment record. * * @return {Object|undefined} Attributes to apply, if any. */ function getNewAttachmentLinkAttributes(linkDestination, attachment) { if (linkDestination === LINK_DESTINATION_MEDIA) return attachment.source_url ? { href: attachment.source_url } : void 0; if (linkDestination === LINK_DESTINATION_ATTACHMENT) return attachment.link ? { href: attachment.link } : void 0; } /** * Resolves the block attributes that are derived from the attachment, for an * edit that saved to a different one. * * Editing media (crop, rotate, flip) creates a new attachment with its own * generated sub-sizes and its own attachment page, and the media editor * reports the full-size file. Without re-deriving these, the size control * keeps reporting e.g. "Medium" while the block renders the full-size image, * and a "Media file" or "Attachment page" link still points at the image as it * was before the edit. Everything else the user set on the block — dimensions, * lightbox, title, custom links — is left untouched. * * @param {Object} blockAttributes The block's current attributes. * @param {Object|undefined} attachment The new attachment record. * * @return {Object|undefined} Attributes to apply, or undefined when the * attachment record isn't known yet. */ function getNewAttachmentImageBlockAttributes(blockAttributes, attachment) { if (!attachment) return; return { ...getNewAttachmentSizeAttributes(blockAttributes.sizeSlug, attachment), ...getNewAttachmentLinkAttributes(blockAttributes.linkDestination, attachment) }; } const { openMediaEditorModalKey } = unlock(privateApis); function getAttachmentFallbackForEmptyBlockMetadata({ alt, caption }) { const attachment = {}; if (!alt) attachment.alt_text = ""; if (!caption?.toString()) attachment.caption = ""; return Object.keys(attachment).length ? attachment : void 0; } function hasKnownAttachmentMetadata(attachment) { if (!attachment) return false; const hasKnownAlt = typeof attachment.alt_text === "string" || typeof attachment.alt === "string"; const hasKnownCaption = getImageBlockMetadataFromAttachment(attachment).caption !== void 0; return hasKnownAlt && hasKnownCaption; } function useOpenImageMediaEditorModal({ attributes, setAttributes, onClose, onUrlChange }) { const { id, url, alt, caption, sizeSlug, linkDestination, href } = attributes; const registry = useRegistry(); const openMediaEditorModal = useSelect((select) => select(store$1).getSettings()[openMediaEditorModalKey], []); const blockAttributesRef = useRef({ id, url, alt, caption: caption?.toString(), sizeSlug, linkDestination, href }); const mediaEditorMetadataBaselineRef = useRef(); const mediaEditorMetadataSyncRequestRef = useRef(0); useEffect(() => { blockAttributesRef.current = { id, url, alt, caption: caption?.toString(), sizeSlug, linkDestination, href }; }, [ alt, caption, href, id, linkDestination, sizeSlug, url ]); const getCachedAttachmentRecord = useCallback((attachmentId) => registry.select(store).getEditedEntityRecord("postType", "attachment", attachmentId), [registry]); const resolveAttachmentRecord = useCallback(async (attachmentId) => { const resolveSelect = registry.resolveSelect(store); try { return await resolveSelect.getEntityRecord("postType", "attachment", attachmentId); } catch { return; } }, [registry]); const resolveFreshAttachmentRecord = useCallback(async (attachmentId) => { const { invalidateResolution } = registry.dispatch(store); invalidateResolution("getEntityRecord", [ "postType", "attachment", attachmentId ]); return resolveAttachmentRecord(attachmentId); }, [registry, resolveAttachmentRecord]); const handleMediaUpdate = useCallback(async ({ id: newId, url: newUrl }, undoState) => { if (typeof newId !== "number") return; const originalAttachment = mediaEditorMetadataBaselineRef.current; mediaEditorMetadataBaselineRef.current = void 0; const syncRequest = ++mediaEditorMetadataSyncRequestRef.current; const nextAttributes = {}; const currentBlockAttributes = blockAttributesRef.current; const isNewAttachment = newId !== currentBlockAttributes.id; if (isNewAttachment) { undoState.undoAttributes.id = currentBlockAttributes.id; undoState.undoAttributes.url = currentBlockAttributes.url; nextAttributes.id = newId; nextAttributes.url = newUrl ?? currentBlockAttributes.url; if (nextAttributes.url !== currentBlockAttributes.url) onUrlChange?.(nextAttributes.url); blockAttributesRef.current = { ...blockAttributesRef.current, id: nextAttributes.id, url: nextAttributes.url }; } if (originalAttachment || isNewAttachment) { const resolvedAttachment = await resolveFreshAttachmentRecord(newId); if (undoState.isUndone || syncRequest !== mediaEditorMetadataSyncRequestRef.current) return; const attachmentRecord = resolvedAttachment ?? getCachedAttachmentRecord(newId); const latestBlockAttributes = blockAttributesRef.current; if (originalAttachment) { const resolvedMetadataAttributes = getSyncedImageBlockAttributes(latestBlockAttributes, originalAttachment, attachmentRecord); if (Object.keys(resolvedMetadataAttributes).length) Object.assign(nextAttributes, resolvedMetadataAttributes); } if (isNewAttachment) { const derivedAttributes = getNewAttachmentImageBlockAttributes(latestBlockAttributes, attachmentRecord); if (derivedAttributes) { Object.assign(nextAttributes, derivedAttributes); if (derivedAttributes.url && derivedAttributes.url !== latestBlockAttributes.url) onUrlChange?.(derivedAttributes.url); } } } if (Object.keys(nextAttributes).length) { for (const key of Object.keys(nextAttributes)) if (!Object.hasOwn(undoState.undoAttributes, key)) undoState.undoAttributes[key] = blockAttributesRef.current[key]; blockAttributesRef.current = { ...blockAttributesRef.current, ...nextAttributes }; setAttributes(nextAttributes); } }, [ getCachedAttachmentRecord, onUrlChange, resolveFreshAttachmentRecord, setAttributes ]); const openImageMediaEditorModal = useCallback(async () => { if (!id || !openMediaEditorModal) return; const cachedAttachmentRecord = getCachedAttachmentRecord(id); const fallbackAttachmentRecord = getAttachmentFallbackForEmptyBlockMetadata(blockAttributesRef.current); const resolvedAttachmentRecord = hasKnownAttachmentMetadata(cachedAttachmentRecord) ? void 0 : await resolveAttachmentRecord(id); mediaEditorMetadataBaselineRef.current = resolvedAttachmentRecord || (hasKnownAttachmentMetadata(cachedAttachmentRecord) ? cachedAttachmentRecord : fallbackAttachmentRecord) || cachedAttachmentRecord; const undoState = { undoAttributes: {}, isUndone: false }; openMediaEditorModal({ id, onUpdate: (updated) => handleMediaUpdate(updated, undoState), onUndo: () => { undoState.isUndone = true; const { undoAttributes } = undoState; if (Object.hasOwn(undoAttributes, "url")) onUrlChange?.(undoAttributes.url); blockAttributesRef.current = { ...blockAttributesRef.current, ...undoAttributes }; setAttributes(undoAttributes); }, onClose }); }, [ getCachedAttachmentRecord, handleMediaUpdate, id, onClose, onUrlChange, openMediaEditorModal, resolveAttachmentRecord, setAttributes ]); return id && openMediaEditorModal ? openImageMediaEditorModal : void 0; } export { getImageBlockMetadataFromAttachment, getNewAttachmentImageBlockAttributes, getSyncedImageBlockAttributes, useOpenImageMediaEditorModal }; //# sourceMappingURL=use-open-image-media-editor-modal.mjs.map