-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathuse-styles-for-block.js
More file actions
107 lines (97 loc) · 2.57 KB
/
use-styles-for-block.js
File metadata and controls
107 lines (97 loc) · 2.57 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* WordPress dependencies
*/
import { useDispatch, useSelect } from '@wordpress/data';
import {
cloneBlock,
getBlockType,
getBlockFromExample,
store as blocksStore,
} from '@wordpress/blocks';
import { useMemo } from '@wordpress/element';
/**
* Internal dependencies
*/
import { getActiveStyle, getRenderedStyles, replaceActiveStyle } from './utils';
import { store as blockEditorStore } from '../../store';
/**
*
* @param {WPBlock} block Block object.
* @param {WPBlockType} type Block type settings.
* @return {WPBlock} A generic block ready for styles preview.
*/
function useGenericPreviewBlock( block, type ) {
return useMemo( () => {
const example = type?.example;
const blockName = type?.name;
if ( example && blockName ) {
return getBlockFromExample( blockName, {
attributes: example.attributes,
innerBlocks: example.innerBlocks,
} );
}
if ( block ) {
return cloneBlock( block );
}
}, [ type?.example ? block?.name : block, type ] );
}
/**
* @typedef useStylesForBlocksArguments
* @property {string} clientId Block client ID.
* @property {() => void} onSwitch Block style switch callback function.
*/
/**
*
* @param {useStylesForBlocksArguments} useStylesForBlocks arguments.
* @return {Object} Results of the select methods.
*/
export default function useStylesForBlocks( { clientId, onSwitch } ) {
const selector = ( select ) => {
const { getBlock } = select( blockEditorStore );
const block = getBlock( clientId );
if ( ! block ) {
return {};
}
const blockType = getBlockType( block.name );
const { getBlockStyles } = select( blocksStore );
return {
block,
blockType,
styles: getBlockStyles( block.name ),
className: block.attributes.className || '',
isFullscreenActive: select( 'core/edit-post' ).isFeatureActive(
'fullscreenMode'
),
};
};
const {
styles,
block,
blockType,
className,
isFullscreenActive,
} = useSelect( selector, [ clientId ] );
const { updateBlockAttributes } = useDispatch( blockEditorStore );
const stylesToRender = getRenderedStyles( styles );
const activeStyle = getActiveStyle( stylesToRender, className );
const genericPreviewBlock = useGenericPreviewBlock( block, blockType );
const onSelect = ( style ) => {
const styleClassName = replaceActiveStyle(
className,
activeStyle,
style
);
updateBlockAttributes( clientId, {
className: styleClassName,
} );
onSwitch();
};
return {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className,
isFullscreenActive,
};
}