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 / Draft / hooks / useSelectedText.js

useSelectedText.js in Extendify 2.2.0, at src/Draft/hooks/useSelectedText.js

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