-
Notifications
You must be signed in to change notification settings - Fork 810
/
Copy pathindex.js
106 lines (99 loc) · 2.61 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* External Dependencies
*/
import classnames from 'classnames';
import { isEqual } from 'lodash';
/**
* WordPress dependencies
*/
import { memo } from '@wordpress/element';
import { getBlockType, getBlockFromExample, createBlock } from '@wordpress/blocks';
import { BlockPreview } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { ENTER, SPACE } from '@wordpress/keycodes';
const addPreviewAttribute = block => {
return {
...block,
attributes: {
...block.attributes,
__isBlockPreview: true,
},
};
};
const StylePreview = ( { attributes, styleOption, viewportWidth, blockName } ) => {
const type = getBlockType( blockName );
return (
<div className="block-editor-block-styles__item-preview">
<BlockPreview
viewportWidth={ viewportWidth }
blocks={ addPreviewAttribute(
type.example
? getBlockFromExample( blockName, {
attributes: { ...type.example.attributes, style: styleOption.value },
innerBlocks: type.example.innerBlocks,
} )
: createBlock( blockName, attributes )
) }
/>
</div>
);
};
const StylePreviewComponent = memo
? memo( StylePreview, ( prevProps, nextProps ) => isEqual( prevProps, nextProps ) )
: StylePreview;
export default function BlockStylesSelector( {
attributes,
clientId,
styleOptions,
onSelectStyle,
activeStyle,
viewportWidth,
} ) {
let block;
if ( useSelect ) {
block = useSelect( select => {
const { getBlock } = select( 'core/block-editor' );
return getBlock( clientId );
} );
}
return (
<div className="block-editor-block-styles">
{ styleOptions.map( styleOption => {
const optionAttributes = {
...attributes,
style: styleOption.value,
};
return (
<div
key={ styleOption.value }
className={ classnames( 'block-editor-block-styles__item', {
'is-active': styleOption.value === activeStyle,
} ) }
onClick={ () => {
onSelectStyle( { style: styleOption.value } );
} }
onKeyDown={ event => {
if ( ENTER === event.keyCode || SPACE === event.keyCode ) {
event.preventDefault();
onSelectStyle( { style: styleOption.value } );
}
} }
role="button"
tabIndex="0"
aria-label={ styleOption.label }
>
{ useSelect && block && (
<StylePreviewComponent
blockName={ block.name }
styleOption={ styleOption }
attributes={ optionAttributes }
viewportWidth={ viewportWidth }
/>
) }
<div className="block-editor-block-styles__item-label">{ styleOption.label }</div>
</div>
);
} ) }
</div>
);
}