| 1 |
import { serialize, rawHandler } from '@wordpress/blocks'; |
| 2 |
|
| 3 |
export const walkAndUpdateImageDetails = (inputs, newImage) => { |
| 4 |
const blocks = rawHandler({ HTML: inputs.previousContent }); |
| 5 |
const parser = new DOMParser(); |
| 6 |
const walk = (blocks) => |
| 7 |
blocks.map((block) => { |
| 8 |
if (['core/image', 'core/cover'].includes(block.name)) { |
| 9 |
const attrs = { ...block.attributes }; |
| 10 |
const url = inputs.url.includes('unsplash.com') |
| 11 |
? inputs.url.split('?')[0] // For unsplash just match the base URL |
| 12 |
: inputs.url; |
| 13 |
const isMatchingId = attrs.id === inputs.imageId; |
| 14 |
const isMatchingUrl = attrs.url.startsWith(url); |
| 15 |
if (!isMatchingId && !isMatchingUrl) { |
| 16 |
// Not our image, return as is |
| 17 |
return { ...block, attributes: attrs }; |
| 18 |
} |
| 19 |
attrs.url = newImage.source_url || newImage.url; |
| 20 |
attrs.id = newImage.id; |
| 21 |
// Remove import class if present |
| 22 |
if (attrs.className) { |
| 23 |
attrs.className = attrs.className |
| 24 |
.split(' ') |
| 25 |
.filter((cn) => cn !== 'extendify-image-import') |
| 26 |
.join(' '); |
| 27 |
} |
| 28 |
// originalContent needs wp-image-{id} to match the new ID |
| 29 |
const originalContentDoc = parser.parseFromString( |
| 30 |
attrs.originalContent || block.originalContent || '', |
| 31 |
'text/html', |
| 32 |
); |
| 33 |
const img = originalContentDoc.querySelector('img'); |
| 34 |
if (!img) return { ...block, attributes: attrs }; |
| 35 |
// cover block wont have an image here |
| 36 |
img.setAttribute('src', newImage.source_url || newImage.url); |
| 37 |
const classList = img.className |
| 38 |
.split(' ') |
| 39 |
.filter((cn) => cn !== `wp-image-${inputs.imageId}`); |
| 40 |
classList.push(`wp-image-${newImage.id}`); |
| 41 |
img.className = classList.join(' '); |
| 42 |
attrs.originalContent = originalContentDoc.body.innerHTML; |
| 43 |
|
| 44 |
return { ...block, attributes: attrs }; |
| 45 |
} |
| 46 |
if (block.innerBlocks && block.innerBlocks.length > 0) { |
| 47 |
return { |
| 48 |
...block, |
| 49 |
innerBlocks: walk(block.innerBlocks), |
| 50 |
}; |
| 51 |
} |
| 52 |
return block; |
| 53 |
}); |
| 54 |
const updatedBlocks = walk(blocks); |
| 55 |
return serialize(updatedBlocks); |
| 56 |
}; |
| 57 |
|