-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
62 lines (52 loc) · 1.48 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
import { useMemo } from 'react';
import { useSelect } from '@wordpress/data';
import { useBlockStyles } from '../..';
const pattern = /^is-style-/;
/**
* Parse the given class name string into a list of valid block styles.
*
* @param {string} className - Class name string.
* @returns {string[]} List of block styles.
*/
function parseClassName( className = '' ) {
return className
.trim()
.replace( /\s+/, ' ' )
.split( ' ' )
.map( ( className ) => pattern.test( className ) ? className.replace( pattern, '' ) : '' )
.filter( Boolean );
}
/**
* Get the active block style for the block with the given client ID.
*
* @param {string} clientId - Block client ID.
* @returns {string} Active block style.
*/
export default function useActiveBlockStyle( clientId ) {
const { blockName, className } = useSelect(
( select ) => {
const block = select( 'core/block-editor' ).getBlock( clientId );
return {
blockName: block?.name ?? '',
className: block?.attributes?.className ?? '',
};
},
[ clientId ]
);
const {
blockStyles,
defaultStyle,
} = useBlockStyles( blockName );
const blockStyleNames = useMemo(
() => blockStyles.map( ( { name } ) => name ),
[ blockStyles ]
);
const currentBlockStyles = useMemo(
() => parseClassName( className ),
[ className ]
);
return useMemo(
() => currentBlockStyles.find( ( blockStyle ) => blockStyleNames.includes( blockStyle ) ) ?? defaultStyle,
[ blockStyleNames, currentBlockStyles, defaultStyle ]
);
}