| 1 |
/** Recursively builds a unique duotone to the parent map from the block tree. */ |
| 2 |
export const getDynamicDuotoneMap = (blocks) => { |
| 3 |
const map = new Map(); |
| 4 |
const seen = new Set(); |
| 5 |
const duotonePrefix = 'var:preset|duotone|'; |
| 6 |
const duotonePrefixLength = duotonePrefix.length; |
| 7 |
|
| 8 |
const scan = (blocks) => { |
| 9 |
if (!blocks || !blocks.length) return; |
| 10 |
|
| 11 |
for (const block of blocks) { |
| 12 |
if (block.name !== 'core/image') { |
| 13 |
scan(block.innerBlocks || []); |
| 14 |
continue; |
| 15 |
} |
| 16 |
|
| 17 |
const url = block.attributes?.url || ''; |
| 18 |
if ( |
| 19 |
!url || |
| 20 |
!url.startsWith('data:image/svg+xml;') || |
| 21 |
seen.has(block.clientId) |
| 22 |
) { |
| 23 |
scan(block.innerBlocks || []); |
| 24 |
continue; |
| 25 |
} |
| 26 |
|
| 27 |
// slice the duotone value to remove the prefix and get the slug |
| 28 |
const duotoneValue = block.attributes?.style?.color?.duotone; |
| 29 |
const duotone = duotoneValue?.startsWith(duotonePrefix) |
| 30 |
? duotoneValue.slice(duotonePrefixLength) |
| 31 |
: null; |
| 32 |
|
| 33 |
const parents = getImageParentsByBlockIdAndUrl( |
| 34 |
block.clientId, |
| 35 |
url, |
| 36 |
)?.filter(Boolean); |
| 37 |
|
| 38 |
if (duotone && parents.length && !map.has(duotone)) { |
| 39 |
parents.forEach((parent) => { |
| 40 |
map.set(parent, duotone); |
| 41 |
}); |
| 42 |
} |
| 43 |
seen.add(block.clientId); |
| 44 |
|
| 45 |
scan(block.innerBlocks || []); |
| 46 |
} |
| 47 |
}; |
| 48 |
|
| 49 |
scan(blocks); |
| 50 |
return Object.fromEntries(map); |
| 51 |
}; |
| 52 |
|
| 53 |
const getDoc = () => |
| 54 |
document.querySelector('iframe[name="editor-canvas"]')?.contentDocument || |
| 55 |
document; |
| 56 |
|
| 57 |
const getImageParentsByBlockIdAndUrl = (id, url) => { |
| 58 |
const doc = getDoc(); |
| 59 |
if (!doc) return []; |
| 60 |
|
| 61 |
const blockElement = doc.querySelector(`[data-block="${id}"]`); |
| 62 |
if (blockElement?.classList) { |
| 63 |
const duotoneClass = []; |
| 64 |
for (const cls of blockElement.classList) { |
| 65 |
if (cls.startsWith('wp-duotone-')) duotoneClass.push(cls); |
| 66 |
} |
| 67 |
if (duotoneClass.length) return duotoneClass; |
| 68 |
} |
| 69 |
|
| 70 |
const images = doc.querySelectorAll(`img[src="${url}"]`); |
| 71 |
const elements = []; |
| 72 |
|
| 73 |
for (const image of images) { |
| 74 |
const parent = image.closest('figure[data-block]'); |
| 75 |
if (parent?.classList) { |
| 76 |
for (const cls of parent.classList) { |
| 77 |
if (cls.startsWith('wp-duotone-')) elements.push(cls); |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
return elements; |
| 83 |
}; |
| 84 |
|