useDynamicContent.js
4 years ago
usePostRecord.js
3 years ago
usePostTypeRecords.js
3 years ago
usePostTypes.js
4 years ago
useDynamicContent.js
64 lines
| 1 | import { __, sprintf } from '@wordpress/i18n'; |
| 2 | import { useEntityProp } from '@wordpress/core-data'; |
| 3 | import getContent from '../utils/getContent'; |
| 4 | import usePostRecord from './usePostRecord'; |
| 5 | |
| 6 | function getExtraLoad( contentType, attributes ) { |
| 7 | const load = []; |
| 8 | let loadOptions = {}; |
| 9 | |
| 10 | if ( contentType.startsWith( 'author-' ) ) { |
| 11 | load.push( 'author' ); |
| 12 | } |
| 13 | |
| 14 | if ( 'terms' === contentType ) { |
| 15 | load.push( 'terms' ); |
| 16 | loadOptions = Object.assign( {}, loadOptions, { taxonomy: attributes.termTaxonomy } ); |
| 17 | } |
| 18 | |
| 19 | if ( 'comments-number' === contentType ) { |
| 20 | load.push( 'comments' ); |
| 21 | } |
| 22 | |
| 23 | return { load, loadOptions }; |
| 24 | } |
| 25 | |
| 26 | export default ( attributes, name ) => { |
| 27 | const { postId, postType } = attributes; |
| 28 | |
| 29 | if ( ! postType ) { |
| 30 | return __( 'Post type not selected.', 'generateblocks' ); |
| 31 | } |
| 32 | |
| 33 | if ( postType && ! postId ) { |
| 34 | return __( 'Post source not selected.', 'generateblocks' ); |
| 35 | } |
| 36 | |
| 37 | const [ siteFormat ] = useEntityProp( 'root', 'site', 'date_format' ); |
| 38 | |
| 39 | const { load, loadOptions } = getExtraLoad( attributes.dynamicContentType, attributes ); |
| 40 | const { record, isLoading } = usePostRecord( postType, postId, load, loadOptions ); |
| 41 | |
| 42 | if ( 'generateblocks/image' === name && ! record ) { |
| 43 | return undefined; |
| 44 | } |
| 45 | |
| 46 | if ( isLoading ) { |
| 47 | return __( 'Loading…', 'generateblocks' ); |
| 48 | } |
| 49 | |
| 50 | if ( ! record ) { |
| 51 | return sprintf( |
| 52 | // translators: %1$s: post ID, %2$s: post type. |
| 53 | __( 'Post of id #%1$s and post type %2$s was not found.', 'generateblocks' ), |
| 54 | postId, |
| 55 | postType |
| 56 | ); |
| 57 | } |
| 58 | |
| 59 | const contentAttributes = Object.assign( {}, attributes, { dateFormat: siteFormat } ); |
| 60 | const forceEmptyMessage = 'generateblocks/image' === name; |
| 61 | |
| 62 | return getContent( attributes.dynamicContentType, record, contentAttributes, forceEmptyMessage ); |
| 63 | }; |
| 64 |