AuthorMetaControl.js
3 years ago
CommentsControl.js
4 years ago
ContentTypeControl.js
4 years ago
DynamicSourceControl.js
3 years ago
ExcerptControl.js
4 years ago
LinkTypeControl.js
3 years ago
PostDateControl.js
4 years ago
PostMetaControl.js
3 years ago
TermsControl.js
4 years ago
PostMetaControl.js
65 lines
| 1 | import usePostRecord from '../hooks/usePostRecord'; |
| 2 | import { __ } from '@wordpress/i18n'; |
| 3 | import AdvancedSelect from '../../../components/advanced-select'; |
| 4 | import { applyFilters } from '@wordpress/hooks'; |
| 5 | |
| 6 | export default function PostMetaControl( props ) { |
| 7 | const { |
| 8 | isActive = false, |
| 9 | metaFieldKey = 'metaFieldName', |
| 10 | postType, |
| 11 | postId, |
| 12 | metaFieldName, |
| 13 | setAttributes, |
| 14 | } = props; |
| 15 | |
| 16 | const { record, isLoading } = usePostRecord( postType, postId ); |
| 17 | const value = !! metaFieldName ? { value: metaFieldName, label: metaFieldName } : undefined; |
| 18 | |
| 19 | let options = !! value ? [ value ] : []; |
| 20 | |
| 21 | if ( record && record.meta ) { |
| 22 | options = options.concat( Object |
| 23 | .keys( record.meta ) |
| 24 | .filter( ( metaKey ) => ( metaKey !== metaFieldName ) ) |
| 25 | .map( ( metaKey ) => ( { value: metaKey, label: metaKey } ) ) |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | const afterComponent = applyFilters( |
| 30 | 'generateblocks.editor.dynamicContent.PostMetaControl.afterComponent', |
| 31 | undefined, |
| 32 | props, |
| 33 | record, |
| 34 | ); |
| 35 | |
| 36 | return ( |
| 37 | <> |
| 38 | { isActive && |
| 39 | <> |
| 40 | <AdvancedSelect |
| 41 | id={ 'gblocks-select-post-meta-control' } |
| 42 | label={ __( 'Post meta field', 'generateblocks' ) } |
| 43 | help={ __( 'Live preview is only available to meta exposed to the REST API.', 'generateblocks' ) } |
| 44 | placeholder={ __( 'Choose or add meta key', 'generateblocks' ) } |
| 45 | options={ options } |
| 46 | value={ value } |
| 47 | isSearchable |
| 48 | isCreatable |
| 49 | isClearable |
| 50 | formatCreateLabel={ ( input ) => ( `Add "${ input }"` ) } |
| 51 | isLoading={ isLoading } |
| 52 | onChange={ ( option ) => { |
| 53 | setAttributes( { [ metaFieldKey ]: option?.value || undefined } ); |
| 54 | } } |
| 55 | /> |
| 56 | |
| 57 | { afterComponent } |
| 58 | </> |
| 59 | } |
| 60 | </> |
| 61 | ); |
| 62 | } |
| 63 | |
| 64 | PostMetaControl.displayName = 'PostMetaControl'; |
| 65 |