@wordpress/block-library
Version:
Block library for the WordPress editor.
77 lines (76 loc) • 2.37 kB
JavaScript
import { createBlobURL } from "@wordpress/blob";
import { createBlock } from "@wordpress/blocks";
import { select } from "@wordpress/data";
import { store } from "@wordpress/core-data";
import { escapeEditableHTML } from "@wordpress/escape-html";
import { _x } from "@wordpress/i18n";
import { getFilename } from "@wordpress/url";
// packages/block-library/src/file/transforms.js
const downloadButtonText = _x("Download", "button label");
const toMediaTransform = (blockName, mediaType, srcAttribute) => ({
type: "block",
blocks: [blockName],
isMatch: ({ id }) => {
if (!id) return false;
const { getEntityRecord } = select(store);
const media = getEntityRecord("postType", "attachment", id, { context: "view" });
return !!media && media.mime_type.includes(mediaType);
},
transform: (attributes) => {
return createBlock(blockName, {
[srcAttribute]: attributes.href,
caption: attributes.fileName,
id: attributes.id,
anchor: attributes.anchor
});
}
});
const transforms = {
from: [{
type: "files",
isMatch(files) {
return files.length > 0;
},
priority: 15,
transform: (files) => {
const blocks = [];
files.forEach((file) => {
const blobURL = createBlobURL(file);
if (file.type.startsWith("video/")) blocks.push(createBlock("core/video", { blob: createBlobURL(file) }));
else if (file.type.startsWith("image/")) blocks.push(createBlock("core/image", { blob: createBlobURL(file) }));
else if (file.type.startsWith("audio/")) blocks.push(createBlock("core/audio", { blob: createBlobURL(file) }));
else blocks.push(createBlock("core/file", {
blob: blobURL,
fileName: file.name,
downloadButtonText
}));
});
return blocks;
}
}, {
type: "block",
blocks: [
"core/audio",
"core/video",
"core/image"
],
transform: (attributes) => {
const href = attributes.src ?? attributes.url;
return createBlock("core/file", {
href,
fileName: attributes.caption || escapeEditableHTML(getFilename(href) ?? ""),
textLinkHref: href,
id: attributes.id,
anchor: attributes.anchor,
downloadButtonText
});
}
}],
to: [
toMediaTransform("core/audio", "audio", "src"),
toMediaTransform("core/video", "video", "src"),
toMediaTransform("core/image", "image", "url")
]
};
export { transforms as default };
//# sourceMappingURL=transforms.mjs.map