-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-advanced-inspector-field-wp-5x.js
58 lines (52 loc) · 1.73 KB
/
add-advanced-inspector-field-wp-5x.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
/* jshint esversion: 6 */
/**
* https://github.com/WordPress/gutenberg/blob/359858da0675943d8a759a0a7c03e7b3846536f5/packages/block-editor/src/hooks/custom-class-name.js
* This uses the hooks defined in the above file to inject the control field in the global advanced inspector area.
*/
import { assign } from 'lodash';
const { Fragment } = wp.element;
const { InspectorAdvancedControls } = wp.editor;
const { TextControl } = wp.components;
const { __ } = wp.i18n;
const { addFilter } = wp.hooks;
const { createHigherOrderComponent } = wp.compose;
const addCustomIDField = createHigherOrderComponent( (BlockEdit) => {
return props => {
return (
<Fragment>
<BlockEdit { ...props } />
<InspectorAdvancedControls>
<TextControl
label={ __('Custom ID', 'domain') }
value={ props.attributes.customID || '' }
onChange={ newValue => {
props.setAttributes({
customID: newValue !== '' ? sanitizeCustomID(newValue) : undefined,
});
}}
/>
</InspectorAdvancedControls>
</Fragment>
);
}
}, 'withInspectorControl');
addFilter('editor.BlockEdit', 'core/editor/custom-class-name/with-inspector-control', addCustomIDField);
function addCustomID(settings, name){
settings.attributes = assign(settings.attributes, {
customID: {
type: 'string',
}
});
return settings;
}
addFilter('blocks.registerBlockType', 'core/custom-class-name/attribute', addCustomID);
function outputCustomID(extras, block, attributes){
if(attributes.customID){
extras.id = attributes.customID;
}
return extras;
}
addFilter('blocks.getSaveContent.extraProps', 'core/custom-class-name/save-props', outputCustomID);
function sanitizeCustomID(val){
return val.replace(/\s+/, '-').replace(/[^a-z0-9-]/gi, '');
}