| 1 |
import { store as blockEditorStore } from '@wordpress/block-editor'; |
| 2 |
import { useSelect } from '@wordpress/data'; |
| 3 |
import { useCallback } from '@wordpress/element'; |
| 4 |
|
| 5 |
const htmlToText = (html) => { |
| 6 |
try { |
| 7 |
const parser = new DOMParser(); |
| 8 |
const doc = parser.parseFromString(html, 'text/html'); |
| 9 |
return doc.body.textContent || ''; |
| 10 |
} catch (_error) { |
| 11 |
return ''; |
| 12 |
} |
| 13 |
}; |
| 14 |
|
| 15 |
export const useSelectedText = () => { |
| 16 |
const { getSelectedBlockClientIds, getBlocksByClientId } = useSelect( |
| 17 |
(select) => select(blockEditorStore), |
| 18 |
[], |
| 19 |
); |
| 20 |
|
| 21 |
const selectedBlockId = getSelectedBlockClientIds(); |
| 22 |
|
| 23 |
const getSelectedContent = useCallback(() => { |
| 24 |
const selectedBlocks = getBlocksByClientId(selectedBlockId); |
| 25 |
if (!selectedBlocks?.length) return ''; |
| 26 |
const raw = selectedBlocks |
| 27 |
.filter(Boolean) |
| 28 |
.map(({ attributes }) => attributes?.content ?? '') |
| 29 |
.join('\n\n'); |
| 30 |
return htmlToText(raw); |
| 31 |
}, [getBlocksByClientId, selectedBlockId]); |
| 32 |
|
| 33 |
return { selectedText: getSelectedContent().trim() }; |
| 34 |
}; |
| 35 |
|