@wordpress/block-library
Version:
Block library for the WordPress editor.
269 lines (268 loc) • 12.1 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_core_data = require("@wordpress/core-data");
let _wordpress_block_editor = require("@wordpress/block-editor");
let _wordpress_dom = require("@wordpress/dom");
let _wordpress_data = require("@wordpress/data");
let _wordpress_element = require("@wordpress/element");
let ___lock_unlock_ts = require("../lock-unlock.cjs");
let __constants_js = require("./constants.cjs");
// packages/block-library/src/image/use-open-image-media-editor-modal.js
function normalizeImageBlockCaption(caption) {
if (typeof caption !== "string") return "";
if (!(0, _wordpress_dom.__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 === __constants_js.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: __constants_js.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 === __constants_js.LINK_DESTINATION_MEDIA) return attachment.source_url ? { href: attachment.source_url } : void 0;
if (linkDestination === __constants_js.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 } = (0, ___lock_unlock_ts.unlock)(_wordpress_block_editor.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 = (0, _wordpress_data.useRegistry)();
const openMediaEditorModal = (0, _wordpress_data.useSelect)((select) => select(_wordpress_block_editor.store).getSettings()[openMediaEditorModalKey], []);
const blockAttributesRef = (0, _wordpress_element.useRef)({
id,
url,
alt,
caption: caption?.toString(),
sizeSlug,
linkDestination,
href
});
const mediaEditorMetadataBaselineRef = (0, _wordpress_element.useRef)();
const mediaEditorMetadataSyncRequestRef = (0, _wordpress_element.useRef)(0);
(0, _wordpress_element.useEffect)(() => {
blockAttributesRef.current = {
id,
url,
alt,
caption: caption?.toString(),
sizeSlug,
linkDestination,
href
};
}, [
alt,
caption,
href,
id,
linkDestination,
sizeSlug,
url
]);
const getCachedAttachmentRecord = (0, _wordpress_element.useCallback)((attachmentId) => registry.select(_wordpress_core_data.store).getEditedEntityRecord("postType", "attachment", attachmentId), [registry]);
const resolveAttachmentRecord = (0, _wordpress_element.useCallback)(async (attachmentId) => {
const resolveSelect = registry.resolveSelect(_wordpress_core_data.store);
try {
return await resolveSelect.getEntityRecord("postType", "attachment", attachmentId);
} catch {
return;
}
}, [registry]);
const resolveFreshAttachmentRecord = (0, _wordpress_element.useCallback)(async (attachmentId) => {
const { invalidateResolution } = registry.dispatch(_wordpress_core_data.store);
invalidateResolution("getEntityRecord", [
"postType",
"attachment",
attachmentId
]);
return resolveAttachmentRecord(attachmentId);
}, [registry, resolveAttachmentRecord]);
const handleMediaUpdate = (0, _wordpress_element.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 = (0, _wordpress_element.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;
}
exports.getImageBlockMetadataFromAttachment = getImageBlockMetadataFromAttachment;
exports.getNewAttachmentImageBlockAttributes = getNewAttachmentImageBlockAttributes;
exports.getSyncedImageBlockAttributes = getSyncedImageBlockAttributes;
exports.useOpenImageMediaEditorModal = useOpenImageMediaEditorModal;
//# sourceMappingURL=use-open-image-media-editor-modal.cjs.map