-
Notifications
You must be signed in to change notification settings - Fork 4k
/
use-copy.js
38 lines (34 loc) · 1.1 KB
/
use-copy.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
/**
* WordPress dependencies
*/
import { useRefEffect } from '@wordpress/compose';
import { store as blockEditorStore } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
export default function useCopy( clientId ) {
const { getBlockRootClientId, getBlockName, getBlockAttributes } =
useSelect( blockEditorStore );
return useRefEffect( ( node ) => {
function onCopy( event ) {
// The event propagates through all nested lists, so don't override
// when copying nested list items.
if ( event.clipboardData.getData( '__unstableWrapperBlockName' ) ) {
return;
}
const rootClientId = getBlockRootClientId( clientId );
event.clipboardData.setData(
'__unstableWrapperBlockName',
getBlockName( rootClientId )
);
event.clipboardData.setData(
'__unstableWrapperBlockAttributes',
JSON.stringify( getBlockAttributes( rootClientId ) )
);
}
node.addEventListener( 'copy', onCopy );
node.addEventListener( 'cut', onCopy );
return () => {
node.removeEventListener( 'copy', onCopy );
node.removeEventListener( 'cut', onCopy );
};
}, [] );
}