-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
88 lines (73 loc) · 2.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* WordPress dependencies
*/
import { useRef } from '@wordpress/element';
import { serialize, pasteHandler } from '@wordpress/blocks';
import { documentHasSelection } from '@wordpress/dom';
import { useDispatch, useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import { getPasteEventData } from '../../utils/get-paste-event-data';
function CopyHandler( { children } ) {
const containerRef = useRef();
const {
getBlocksByClientId,
getSelectedBlockClientIds,
hasMultiSelection,
getSettings,
} = useSelect( ( select ) => select( 'core/block-editor' ), [] );
const { removeBlocks, replaceBlocks } = useDispatch( 'core/block-editor' );
const {
__experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML,
} = getSettings();
const handler = ( event ) => {
const selectedBlockClientIds = getSelectedBlockClientIds();
if ( selectedBlockClientIds.length === 0 ) {
return;
}
// Always handle multiple selected blocks.
// Let native copy behaviour take over in input fields.
if ( ! hasMultiSelection() && documentHasSelection() ) {
return;
}
if ( ! containerRef.current.contains( event.target ) ) {
return;
}
event.preventDefault();
if ( event.type === 'copy' || event.type === 'cut' ) {
const blocks = getBlocksByClientId( selectedBlockClientIds );
const serialized = serialize( blocks );
event.clipboardData.setData( 'text/plain', serialized );
event.clipboardData.setData( 'text/html', serialized );
}
if ( event.type === 'cut' ) {
removeBlocks( selectedBlockClientIds );
} else if ( event.type === 'paste' ) {
const { plainText, html } = getPasteEventData( event );
const blocks = pasteHandler( {
HTML: html,
plainText,
mode: 'BLOCKS',
canUserUseUnfilteredHTML,
} );
replaceBlocks(
selectedBlockClientIds,
blocks,
blocks.length - 1,
-1
);
}
};
return (
<div
ref={ containerRef }
onCopy={ handler }
onCut={ handler }
onPaste={ handler }
>
{ children }
</div>
);
}
export default CopyHandler;