import $ from 'jquery'; import rafSchd from 'raf-schd'; import { debounce } from 'throttle-debounce'; import { PanelRow, TextControl } from '@wordpress/components'; import { compose, withInstanceId } from '@wordpress/compose'; import { withDispatch, withSelect } from '@wordpress/data'; import { PluginDocumentSettingPanel } from '@wordpress/edit-post'; import { Component } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { registerPlugin } from '@wordpress/plugins'; const { ajaxurl, VPGutenbergMetaVariables } = window; /** * Component */ class VpVideoComponent extends Component { constructor(props) { super(props); this.state = { oembedQuery: '', oembedHTML: '', }; this.maybePrepareOembed = debounce( 300, rafSchd(this.maybePrepareOembed.bind(this)) ); } componentDidMount() { this.maybePrepareOembed(); } componentDidUpdate() { this.maybePrepareOembed(); } /** * Prepare oEmbed HTML. */ maybePrepareOembed() { const { oembedQuery, oembedHTML } = this.state; const { getMeta, postFormat } = this.props; if (postFormat !== 'video') { return; } const videoUrl = getMeta('_vp_format_video_url'); if (oembedQuery === videoUrl) { return; } // Abort AJAX. if (this.oembedAjax && this.oembedAjax.abort) { this.oembedAjax.abort(); } if (!oembedQuery && oembedHTML) { this.setState({ oembedHTML: '', }); return; } this.oembedAjax = $.ajax({ url: ajaxurl, method: 'POST', dataType: 'json', data: { action: 'vp_find_oembed', q: videoUrl, nonce: VPGutenbergMetaVariables.nonce, }, complete: (data) => { const json = data.responseJSON; const newState = { oembedQuery: videoUrl, oembedHTML: '', }; if (json && typeof json.html !== 'undefined') { newState.oembedHTML = json.html; } this.setState(newState); this.oembedAjax = null; }, }); } render() { const { getMeta, postFormat, updateMeta } = this.props; const { oembedHTML } = this.state; if (postFormat !== 'video') { return null; } return ( } className="vpf-meta-video-panel" >

{sprintf( __( 'Video will be used in %s layouts only. Full list of supported links', 'visual-portfolio' ), VPGutenbergMetaVariables.plugin_name )}   {__('see here', 'visual-portfolio')}

{ updateMeta('_vp_format_video_url', val); }} type="url" placeholder="https://" />
); } } const VpVideo = compose([ withSelect((select) => ({ getMeta(name) { const meta = select('core/editor').getEditedPostAttribute('meta') || {}; return meta[name]; }, postFormat: select('core/editor').getEditedPostAttribute('format'), })), withDispatch((dispatch) => ({ updateMeta(name, val) { dispatch('core/editor').editPost({ meta: { [name]: val } }); }, })), withInstanceId, ])(VpVideoComponent); // Check if editPost available. // For example, on the Widgets screen this variable is not defined. if (wp.editPost) { registerPlugin('vp-video', { render: VpVideo, }); }