-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
use-block-display-title.js
86 lines (79 loc) · 2.24 KB
/
use-block-display-title.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
/**
* External dependencies
*/
import { truncate } from 'lodash';
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';
import {
getBlockType,
__experimentalGetBlockLabel as getBlockLabel,
isReusableBlock,
} from '@wordpress/blocks';
/**
* Internal dependencies
*/
import useBlockDisplayInformation from '../use-block-display-information';
import { store as blockEditorStore } from '../../store';
/**
* Returns the block's configured title as a string, or empty if the title
* cannot be determined.
*
* @example
*
* ```js
* useBlockDisplayTitle( 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', 17 );
* ```
*
* @param {string} clientId Client ID of block.
* @param {number|undefined} maximumLength The maximum length that the block title string may be before truncated.
* @return {?string} Block title.
*/
export default function useBlockDisplayTitle( clientId, maximumLength ) {
const { attributes, name, reusableBlockTitle } = useSelect(
( select ) => {
if ( ! clientId ) {
return {};
}
const {
getBlockName,
getBlockAttributes,
__experimentalGetReusableBlockTitle,
} = select( blockEditorStore );
const blockName = getBlockName( clientId );
if ( ! blockName ) {
return {};
}
const isReusable = isReusableBlock( getBlockType( blockName ) );
return {
attributes: getBlockAttributes( clientId ),
name: blockName,
reusableBlockTitle:
isReusable &&
__experimentalGetReusableBlockTitle(
getBlockAttributes( clientId ).ref
),
};
},
[ clientId ]
);
const blockInformation = useBlockDisplayInformation( clientId );
if ( ! name || ! blockInformation ) {
return null;
}
const blockType = getBlockType( name );
const blockLabel = blockType
? getBlockLabel( blockType, attributes )
: null;
const label = reusableBlockTitle || blockLabel;
// Label will fallback to the title if no label is defined for the current
// label context. If the label is defined we prioritize it over a
// possible block variation title match.
const blockTitle =
label && label !== blockType.title ? label : blockInformation.title;
if ( maximumLength && maximumLength > 0 ) {
return truncate( blockTitle, { length: maximumLength } );
}
return blockTitle;
}