| 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 |
|