| 1 |
import { getRenderingMode, setRenderingMode } from '@agent/lib/editor'; |
| 2 |
import { select } from '@wordpress/data'; |
| 3 |
|
| 4 |
export default async () => { |
| 5 |
const renderingMode = getRenderingMode(); |
| 6 |
// temp disable if user has templates showing |
| 7 |
if (renderingMode === 'template-locked') await setRenderingMode('post-only'); |
| 8 |
const blocks = select('core/block-editor').getBlocks(); |
| 9 |
const title = select('core/editor').getEditedPostAttribute('title'); |
| 10 |
const post_strings = dedupeStrings([ |
| 11 |
title, |
| 12 |
...extractTextFromEditorBlocks(blocks), |
| 13 |
]); |
| 14 |
if (renderingMode === 'template-locked') setRenderingMode('template-locked'); |
| 15 |
return { post_strings }; |
| 16 |
}; |
| 17 |
|
| 18 |
const extractTextFromEditorBlocks = (blocks) => |
| 19 |
blocks.flatMap((block) => [ |
| 20 |
// Extract from relevant string attributes (live editor state) |
| 21 |
...['content', 'caption', 'alt', 'title', 'value'] |
| 22 |
.map((key) => |
| 23 |
typeof block?.attributes?.[key] === 'string' |
| 24 |
? block.attributes[key].trim() |
| 25 |
: null, |
| 26 |
) |
| 27 |
// Might be in rich text |
| 28 |
.map(() => |
| 29 |
typeof block?.attributes?.text?.text === 'string' |
| 30 |
? block.attributes.text.text.trim() |
| 31 |
: null, |
| 32 |
) |
| 33 |
.filter(Boolean), |
| 34 |
// Extract from rendered HTML (if available) |
| 35 |
...(block.originalContent |
| 36 |
? [ |
| 37 |
stripHtml(block.originalContent), |
| 38 |
...extractAltAndTitleFromHtml(block.originalContent), |
| 39 |
].filter(Boolean) |
| 40 |
: []), |
| 41 |
// Recurse into innerBlocks |
| 42 |
...extractTextFromEditorBlocks(block.innerBlocks || []), |
| 43 |
]); |
| 44 |
|
| 45 |
const newSet = (arr) => new Set(arr.filter(Boolean)); |
| 46 |
const dedupeStrings = (arr) => [...newSet(arr)]; |
| 47 |
|
| 48 |
const stripHtml = (html) => |
| 49 |
html |
| 50 |
.replace(/<[^>]+>/g, '') |
| 51 |
.replace(/\s+/g, ' ') |
| 52 |
.trim(); |
| 53 |
|
| 54 |
// Handles image stuff |
| 55 |
const extractAltAndTitleFromHtml = (html) => { |
| 56 |
const matches = []; |
| 57 |
const altMatch = html.match(/alt="([^"]*)"/); |
| 58 |
if (altMatch?.[1]) matches.push(altMatch[1].trim()); |
| 59 |
const titleMatch = html.match(/title="([^"]*)"/); |
| 60 |
if (titleMatch?.[1]) matches.push(titleMatch[1].trim()); |
| 61 |
return matches; |
| 62 |
}; |
| 63 |
|