PluginProbe
Extendify / 3.2.1
Extendify v3.2.1
3.2.1 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 All 127 releases
extendify / src / Agent / workflows / content / tools / get-post-strings.js

get-post-strings.js in Extendify 3.2.1, at src/Agent/workflows/content/tools/get-post-strings.js

57 lines 1.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import apiFetch from '@wordpress/api-fetch';
2 import { parse } from '@wordpress/block-serialization-default-parser';
3
4 export default async ({ postId, postType }) => {
5 const type = postType === 'page' ? 'pages' : 'posts';
6 const response = await apiFetch({
7 path: `/wp/v2/${type}/${postId}?context=edit`,
8 });
9 const blocks = parse(response.content.raw);
10 const postStrings = [response.title.raw, ...extractTextFromBlocks(blocks)];
11
12 return { post_strings: dedupeStrings(postStrings) };
13 };
14
15 const newSet = (arr) => new Set(arr.filter(Boolean));
16 const dedupeStrings = (arr) => [...newSet(arr)];
17
18 const stripHtml = (html) =>
19 html
20 .replace(/<[^>]+>/g, '')
21 .replace(/\s+/g, ' ')
22 .trim();
23
24 // Handles image stuff
25 const extractAltAndTitleFromHtml = (html) => {
26 const matches = [];
27 const altMatch = html.match(/alt="([^"]*)"/);
28 if (altMatch?.[1]) matches.push(altMatch[1].trim());
29 const titleMatch = html.match(/title="([^"]*)"/);
30 if (titleMatch?.[1]) matches.push(titleMatch[1].trim());
31 return matches;
32 };
33
34 const extractTextFromBlocks = (blocks) => {
35 if (!blocks || blocks.length === 0) return [];
36 return blocks.flatMap((block) => [
37 // Extract from innerContent (rendered HTML)
38 ...(block.innerContent
39 ? block.innerContent
40 .filter(Boolean)
41 .flatMap((html) => [
42 stripHtml(html),
43 ...extractAltAndTitleFromHtml(html),
44 ])
45 .filter(Boolean)
46 : []),
47 // Extract from relevant string attributes
48 ...['content', 'caption', 'alt', 'title', 'value']
49 .map((key) =>
50 typeof block.attrs?.[key] === 'string' ? block.attrs[key].trim() : null,
51 )
52 .filter(Boolean),
53 // Recurse into innerBlocks
54 ...extractTextFromBlocks(block.innerBlocks || []),
55 ]);
56 };
57