diff --git a/packages/block-library/src/paragraph/transforms.js b/packages/block-library/src/paragraph/transforms.js index 5179a7f05c22fa..559366526ed865 100644 --- a/packages/block-library/src/paragraph/transforms.js +++ b/packages/block-library/src/paragraph/transforms.js @@ -37,6 +37,53 @@ const transforms = { }, }, ], + to: [ + { + type: 'block', + blocks: [ 'core/image' ], + isMatch: ( { content } ) => { + const div = document.createElement( 'div' ); + div.innerHTML = content; + + const images = div.querySelectorAll( 'img' ); + const hasOnlyImages = + images.length === 1 && + div.childNodes.length === 1 && + div.textContent.trim() === ''; + + return hasOnlyImages; + }, + transform: ( { content, align } ) => { + const div = document.createElement( 'div' ); + div.innerHTML = content; + + const img = div.querySelector( 'img' ); + + const url = img.getAttribute( 'src' ); + const alt = img.getAttribute( 'alt' ); + const title = img.getAttribute( 'title' ); + const width = img.getAttribute( 'width' ); + const height = img.getAttribute( 'height' ); + const className = img.getAttribute( 'class' ); + + return createBlock( 'core/image', { + url, + alt: alt || '', + title: title || '', + align, + width: width ? parseInt( width, 10 ) : undefined, + height: height ? parseInt( height, 10 ) : undefined, + className: className || '', + linkDestination: + img.parentNode.tagName === 'A' ? 'custom' : undefined, + href: + img.parentNode.tagName === 'A' + ? img.parentNode.getAttribute( 'href' ) + : undefined, + } ); + }, + }, + ], }; export default transforms;