| 1 |
import { createBlock } from '@wordpress/blocks'; |
| 2 |
import { select, dispatch } from '@wordpress/data'; |
| 3 |
import { getRenderingMode, setRenderingMode } from '@agent/lib/editor'; |
| 4 |
|
| 5 |
export default async ({ replacements }) => { |
| 6 |
const renderingMode = getRenderingMode(); |
| 7 |
// temp disable if user has templates showing |
| 8 |
if (renderingMode === 'template-locked') await setRenderingMode('post-only'); |
| 9 |
const postTitle = select('core/editor').getEditedPostAttribute('title'); |
| 10 |
const updatedTitle = replaceInString(postTitle, replacements); |
| 11 |
dispatch('core/editor').editPost({ title: updatedTitle }); |
| 12 |
|
| 13 |
const blocks = select('core/block-editor').getBlocks(); |
| 14 |
const changedBlocks = blocks.flatMap((block) => |
| 15 |
findChangedBlocks(block, replacements), |
| 16 |
); |
| 17 |
|
| 18 |
changedBlocks.forEach(({ clientId, block }) => { |
| 19 |
dispatch('core/block-editor').replaceBlock(clientId, block); |
| 20 |
}); |
| 21 |
if (renderingMode === 'template-locked') setRenderingMode('template-locked'); |
| 22 |
return; |
| 23 |
}; |
| 24 |
|
| 25 |
// Supports multiple replacements in a string |
| 26 |
const replaceInString = (str, replacements) => |
| 27 |
replacements |
| 28 |
.filter((r) => r.original !== '') |
| 29 |
.reduce( |
| 30 |
(acc, { original, updated }) => acc.split(original).join(updated), |
| 31 |
str, |
| 32 |
); |
| 33 |
|
| 34 |
const findChangedBlocks = (block, replacements) => { |
| 35 |
const changedBlocks = []; |
| 36 |
const newAttributes = { ...block.attributes }; |
| 37 |
let changed = false; |
| 38 |
|
| 39 |
// Check all these attributes for changes |
| 40 |
['content', 'caption', 'alt', 'title', 'value', 'text'].forEach((key) => { |
| 41 |
const val = newAttributes[key]; |
| 42 |
// Handles rich text and strings |
| 43 |
const str = |
| 44 |
val && typeof val.toString === 'function' ? val.toString() : val; |
| 45 |
if (typeof str === 'string') { |
| 46 |
const replaced = replaceInString(str, replacements); |
| 47 |
if (replaced !== str) { |
| 48 |
newAttributes[key] = replaced; |
| 49 |
changed = true; |
| 50 |
} |
| 51 |
} |
| 52 |
}); |
| 53 |
|
| 54 |
if (changed) { |
| 55 |
// If we found blocks to change, add them to the list |
| 56 |
const newBlock = createBlock(block.name, newAttributes, block.innerBlocks); |
| 57 |
changedBlocks.push({ clientId: block.clientId, block: newBlock }); |
| 58 |
} |
| 59 |
|
| 60 |
// Recursively check inner blocks |
| 61 |
block.innerBlocks.forEach((inner) => { |
| 62 |
changedBlocks.push(...findChangedBlocks(inner, replacements)); |
| 63 |
}); |
| 64 |
|
| 65 |
return changedBlocks; |
| 66 |
}; |
| 67 |
|