diff --git a/projects/plugins/jetpack/changelog/fix-site-editor-podcast-player-block b/projects/plugins/jetpack/changelog/fix-site-editor-podcast-player-block
new file mode 100644
index 000000000000..3c8d7a418cdc
--- /dev/null
+++ b/projects/plugins/jetpack/changelog/fix-site-editor-podcast-player-block
@@ -0,0 +1,4 @@
+Significance: patch
+Type: compat
+
+Ensure compatibility with the Site Editor by injecting required media assets into the Site Editor canvas, and loading frontend scripts onDomReady
diff --git a/projects/plugins/jetpack/extensions/blocks/podcast-player/edit.js b/projects/plugins/jetpack/extensions/blocks/podcast-player/edit.js
index 9ae6439e1823..da9bbba14145 100644
--- a/projects/plugins/jetpack/extensions/blocks/podcast-player/edit.js
+++ b/projects/plugins/jetpack/extensions/blocks/podcast-player/edit.js
@@ -7,7 +7,7 @@ import { debounce, noop } from 'lodash';
/**
* WordPress dependencies
*/
-import { useCallback, useEffect, useRef, useReducer } from '@wordpress/element';
+import { useCallback, useEffect, useState, useRef, useReducer } from '@wordpress/element';
import {
Button,
ExternalLink,
@@ -50,6 +50,7 @@ import { fetchPodcastFeed } from './api';
import { podcastPlayerReducer, actions } from './state';
import { applyFallbackStyles } from '../../shared/apply-fallback-styles';
import { PODCAST_FEED, EMBED_BLOCK } from './constants';
+import { maybeCopyElementsToSiteEditorContext } from '../../shared/block-editor-asset-loader';
const DEFAULT_MIN_ITEMS = 1;
const DEFAULT_MAX_ITEMS = 10;
@@ -94,6 +95,8 @@ const PodcastPlayerEdit = ( {
const playerId = `jetpack-podcast-player-block-${ instanceId }`;
+ const [ hasMigratedStyles, setHasMigratedStyles ] = useState( false );
+
// State.
const cancellableFetch = useRef();
const [ { selectedGuid, checkUrl, ...state }, dispatch ] = useReducer( podcastPlayerReducer, {
@@ -156,12 +159,28 @@ const PodcastPlayerEdit = ( {
[ replaceWithEmbedBlock, setAttributes ]
);
+ // Call once on mount or unmount (the return callback).
useEffect( () => {
return () => {
cancellableFetch?.current?.cancel?.();
};
}, [] );
+ // The Podcast player audio element requires wpmedialement styles.
+ // These aren't available in the Site Editor context, so we have to copy them in.
+ const podCastPlayerRef = useCallback(
+ node => {
+ if ( node !== null && ! hasMigratedStyles ) {
+ maybeCopyElementsToSiteEditorContext(
+ [ 'link#mediaelement-css', 'link#wp-mediaelement-css' ],
+ node
+ );
+ setHasMigratedStyles( true );
+ }
+ },
+ [ hasMigratedStyles ]
+ );
+
// Load RSS feed initially and when the feed or selected episode changes.
useEffect( () => {
// Don't do anything if no url is set.
@@ -374,7 +393,7 @@ const PodcastPlayerEdit = ( {
-
+
{
- player.classList.remove( 'is-default' );
- initializeBlock( player.id );
- } );
+document.addEventListener( 'DOMContentLoaded', () => {
+ document
+ .querySelectorAll( '.wp-block-jetpack-podcast-player:not([data-jetpack-block-initialized])' )
+ .forEach( player => {
+ player.classList.remove( 'is-default' );
+ initializeBlock( player.id );
+ } );
+} );
diff --git a/projects/plugins/jetpack/extensions/shared/block-editor-asset-loader.js b/projects/plugins/jetpack/extensions/shared/block-editor-asset-loader.js
new file mode 100644
index 000000000000..51576f5a9ee0
--- /dev/null
+++ b/projects/plugins/jetpack/extensions/shared/block-editor-asset-loader.js
@@ -0,0 +1,94 @@
+/**
+ * Returns the current document and window contexts for `elementRef`.
+ * Use to retrieve the correct context for elements that may be within an iframe.
+ *
+ * @param {HTMLElement} elementRef - The element whose context we want to return.
+ * @returns {Object} - The current document (`currentDoc`) and window (`currentWindow`) contexts.
+ */
+export function getLoadContext( elementRef ) {
+ const currentDoc = elementRef.ownerDocument;
+ const currentWindow = currentDoc.defaultView || currentDoc.parentWindow;
+
+ return { currentDoc, currentWindow };
+}
+
+/**
+ * Returns whether a given element is contained within an Editor iframe.
+ * See: https://github.com/WordPress/gutenberg/blob/bee52e68292357011a799f067ad47aa1c1d710e1/packages/block-editor/src/components/iframe/index.js
+ *
+ * @param {HTMLElement} elementRef - The element whose context we want to return.
+ * @returns {boolean} - Whether `elementRef` is contained within an Editor iframe.
+ */
+export function isElementInEditorIframe( elementRef ) {
+ const { currentWindow } = getLoadContext( elementRef );
+ return currentWindow.name === 'editor-canvas' && currentWindow.self !== currentWindow.top;
+}
+
+/**
+ * Returns whether a iframe has domain access to its parent.
+ *
+ * @param {HTMLElement} currentWindow - The window context for which we want to test access.
+ * @returns {boolean} - Whether we have access to the parent window.
+ */
+function canIframeAccessParentWindow( currentWindow ) {
+ try {
+ return !! currentWindow?.parent?.location.href;
+ } catch ( e ) {
+ return false;
+ }
+}
+
+/**
+ * This function will check if the current element (e.g., a block) sits inside an Iframe (e.g., the Site Editor)
+ * and tries to move elements from the parent window to the iframe.
+ *
+ * It's a temporary work-around to inject the styles we need for the media player into the site editor.
+ * For use until Gutenberg offers a standardized way of including enqueued/3rd-party assets.
+ * Target usage is the Podcast Playerblock: projects/plugins/jetpack/extensions/blocks/podcast-player/.
+ *
+ * @param {Array} elementSelectors - An array of selectors, e.g., [ '#conan', '#robocop' ]
+ * @param {HTMLElement} elementRef - The current element.
+ * @param {boolean} shouldRemoveSource - Optional. Whether to remove the source element in the parent frame.
+ * @returns {Array} - An array of successfully migrated selectors;
+ */
+export function maybeCopyElementsToSiteEditorContext(
+ elementSelectors,
+ elementRef,
+ shouldRemoveSource = false
+) {
+ let results = [];
+ // Check to see if we're in an iframe, e.g., the Site Editor.
+ // If not, do nothing.
+ if (
+ ! elementRef ||
+ ( ! elementSelectors && ! elementSelectors.length ) ||
+ ! isElementInEditorIframe( elementRef )
+ ) {
+ return results;
+ }
+
+ const { currentDoc, currentWindow } = getLoadContext( elementRef );
+
+ if ( ! canIframeAccessParentWindow( currentWindow ) ) {
+ return results;
+ }
+
+ const parentDoc = currentWindow?.parent?.document;
+
+ if ( currentDoc && parentDoc ) {
+ results = elementSelectors.filter( selector => {
+ const parentElementToCopy = parentDoc.querySelector( selector );
+ const isElementAlreadyPresentInCurrentWindow = !! currentDoc.querySelector( selector );
+ if ( parentElementToCopy && ! isElementAlreadyPresentInCurrentWindow ) {
+ currentDoc.head.appendChild( parentElementToCopy.cloneNode() );
+ if ( shouldRemoveSource ) {
+ parentElementToCopy.remove();
+ }
+ return true;
+ }
+ return false;
+ } );
+
+ return results;
+ }
+}