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 / workflows / content / tools / update-post-strings-editor.js

update-post-strings-editor.js in Extendify 2.2.0, at src/Agent/workflows/content/tools/update-post-strings-editor.js

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