PluginProbe
Extendify / 2.2.0
Extendify v2.2.0
3.2.0 3.1.6 3.1.5 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 3.0.6 3.0.5 3.0.4 trunk 0.1.0 0.10.0 0.10.1 0.10.2 0.11.0 0.11.1 0.2.0 0.3.0 0.3.1 0.4.0 0.5.0 0.6.0 0.7.0 All 126 releases
extendify / src / Agent / lib / blocks.js

blocks.js in Extendify 2.2.0, at src/Agent/lib/blocks.js

57 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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