Skip to content

Instantly share code, notes, and snippets.

@ryanwelcher
Last active November 4, 2024 15:33
Show Gist options
  • Save ryanwelcher/716aeed3a3643bbe19140a6578ac89b4 to your computer and use it in GitHub Desktop.
Save ryanwelcher/716aeed3a3643bbe19140a6578ac89b4 to your computer and use it in GitHub Desktop.
YT embed
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { TextControl } from '@wordpress/components';
import { useEntityProp } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';
import { useBlockProps } from '@wordpress/block-editor';
import { useEffect } from '@wordpress/element';
// Faking the prefix for now
const invp_blocks = {
meta_prefix: 'prefix_',
};
/**
* In order for a block to render HTML stored in a meta value, we need this RawHTML function.
* @link https://wordpress.stackexchange.com/a/409328/13090
*/
// I moved this here because we don't need to redefine this with every render.
const htmlToElem = ( html ) => wp.element.RawHTML( { children: html } );
export default function Edit( { isSelected, context } ) {
// Optional: This can be replaced by using the block's context. Add "usesContext": [ "postType" ] to the block.json file.
const postType = useSelect(
( select ) => select( 'core/editor' ).getCurrentPostType(),
[]
);
// Optional: Context is passed to the block once enabled in block.json.
// const { postType } = context;
const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
const blockProps = useBlockProps();
const metaValue = meta[ invp_blocks.meta_prefix + 'youtube' ];
const metaValueEmbed = meta[ invp_blocks.meta_prefix + 'youtube_embed' ];
// Add a useEffect to handle when the videoID changes
useEffect( () => {
console.log( 'metaValue changed:', metaValue );
// Some basic validation to avoid unnecessary API requests
if ( '' === metaValue || 11 > metaValue.length ) {
return;
}
wp.apiRequest( {
url: wp.media.view.settings.oEmbedProxyUrl,
data: {
url: 'https://www.youtube.com/watch?v=' + metaValue,
},
type: 'GET',
dataType: 'json',
context: this,
} ).done( ( response ) => {
setMeta( {
...meta,
[ invp_blocks.meta_prefix + 'youtube_embed' ]: response.html,
} );
const container = document.getElementById(
blockProps.id + '-oembed'
);
if ( container ) {
container.innerHTML = response.html;
}
} );
}, [ metaValue ] );
return (
<div { ...blockProps }>
{
// I added a ternary operator to switch between the two views.
// The () are used to wrap the JSX returned.
isSelected ? (
<TextControl
label={ __( 'YouTube Video ID', 'inventory-presser' ) }
value={ metaValue }
// onChange={ onChangeId }
onChange={ ( videoId ) =>
setMeta( {
...meta,
[ invp_blocks.meta_prefix + 'youtube' ]:
videoId,
} )
}
/>
) : (
<div id={ blockProps.id + '-oembed' }>
{ htmlToElem( metaValueEmbed ) }
</div>
)
}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment