Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iframe: avoid asset parsing, avoid body replacement, fix script localisation #50913

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 35 additions & 80 deletions packages/block-editor/src/components/iframe/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
/**
* External dependencies
*/
import classnames from 'classnames';

/**
* WordPress dependencies
*/
Expand All @@ -11,7 +6,6 @@ import {
createPortal,
forwardRef,
useMemo,
useReducer,
useEffect,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
Expand Down Expand Up @@ -78,29 +72,6 @@ function bubbleEvents( doc ) {
}
}

function useParsedAssets( html ) {
return useMemo( () => {
const doc = document.implementation.createHTMLDocument( '' );
doc.body.innerHTML = html;
return Array.from( doc.body.children );
}, [ html ] );
}

async function loadScript( head, { id, src } ) {
return new Promise( ( resolve, reject ) => {
const script = head.ownerDocument.createElement( 'script' );
script.id = id;
if ( src ) {
script.src = src;
script.onload = () => resolve();
script.onerror = () => reject();
} else {
resolve();
}
head.appendChild( script );
} );
}

function Iframe( {
contentRef,
children,
Expand All @@ -112,20 +83,25 @@ function Iframe( {
forwardedRef: ref,
...props
} ) {
const assets = useSelect(
const { styles = '', scripts = '' } = useSelect(
( select ) =>
select( blockEditorStore ).getSettings().__unstableResolvedAssets,
select( blockEditorStore ).getSettings().__unstableResolvedAssets ??
{},
[]
);
const [ , forceRender ] = useReducer( () => ( {} ) );
const [ iframeDocument, setIframeDocument ] = useState();
const [ bodyClasses, setBodyClasses ] = useState( [] );
const compatStyles = useCompatibilityStyles();
const scripts = useParsedAssets( assets?.scripts );
const clearerRef = useBlockSelectionClearer();
const [ before, writingFlowRef, after ] = useWritingFlow();
const [ contentResizeListener, { height: contentHeight } ] =
useResizeObserver();
const disabledRef = useDisabled( { isDisabled: ! readonly } );
const bodyRef = useMergeRefs( [
contentRef,
clearerRef,
writingFlowRef,
disabledRef,
] );
const setRef = useRefEffect( ( node ) => {
let iFrameDocument;
// Prevent the default browser action for files dropped outside of dropzones.
Expand All @@ -140,21 +116,31 @@ function Iframe( {
bubbleEvents( contentDocument );
setIframeDocument( contentDocument );
clearerRef( documentElement );
bodyRef( contentDocument.body );

contentDocument.body.classList.add( 'wp-block-editor__iframe' );
contentDocument.body.classList.add( 'editor-styles-wrapper' );

contentDocument.body.addEventListener( 'click', ( event ) => {
if ( event.target === contentDocument.body ) {
node.click();
}
} );

// Ideally ALL classes that are added through get_body_class should
// be added in the editor too, which we'll somehow have to get from
// the server in the future (which will run the PHP filters).
setBodyClasses(
Array.from( ownerDocument.body.classList ).filter(
( name ) =>
name.startsWith( 'admin-color-' ) ||
name.startsWith( 'post-type-' ) ||
name === 'wp-embed-responsive'
)
);
for ( const className of ownerDocument.body.classList ) {
if (
className.startsWith( 'admin-color-' ) ||
className.startsWith( 'post-type-' ) ||
className === 'wp-embed-responsive'
) {
contentDocument.body.classList.add( className );
}
}

contentDocument.dir = ownerDocument.dir;
documentElement.removeChild( contentDocument.body );

for ( const compatStyle of compatStyles ) {
if ( contentDocument.getElementById( compatStyle.id ) ) {
Expand Down Expand Up @@ -199,35 +185,14 @@ function Iframe( {
};
}, [] );

const headRef = useRefEffect( ( element ) => {
scripts
.reduce(
( promise, script ) =>
promise.then( () => loadScript( element, script ) ),
Promise.resolve()
)
.finally( () => {
// When script are loaded, re-render blocks to allow them
// to initialise.
forceRender();
} );
}, [] );
const disabledRef = useDisabled( { isDisabled: ! readonly } );
const bodyRef = useMergeRefs( [
contentRef,
clearerRef,
writingFlowRef,
disabledRef,
headRef,
] );

// Correct doctype is required to enable rendering in standards
// mode. Also preload the styles to avoid a flash of unstyled
// content.
const html =
'<!doctype html>' +
'<style>html{height:auto!important;min-height:100%;}body{margin:0}</style>' +
( assets?.styles ?? '' );
'<style>html{height:auto!important;}body{margin:0}</style>' +
styles +
scripts;

const [ src, cleanup ] = useMemo( () => {
const _src = URL.createObjectURL(
Expand Down Expand Up @@ -267,28 +232,18 @@ function Iframe( {
} }
ref={ useMergeRefs( [ ref, setRef ] ) }
tabIndex={ tabIndex }
// Correct doctype is required to enable rendering in standards
// mode. Also preload the styles to avoid a flash of unstyled
// content.
src={ src }
title={ __( 'Editor canvas' ) }
>
{ iframeDocument &&
createPortal(
<body
ref={ bodyRef }
className={ classnames(
'block-editor-iframe__body',
'editor-styles-wrapper',
...bodyClasses
) }
>
<>
{ contentResizeListener }
<StyleProvider document={ iframeDocument }>
{ children }
</StyleProvider>
</body>,
iframeDocument.documentElement
</>,
iframeDocument.body
) }
</iframe>
{ tabIndex >= 0 && after }
Expand Down
13 changes: 13 additions & 0 deletions packages/e2e-tests/plugins/iframed-enqueue-block-assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,18 @@ static function() {
filemtime( plugin_dir_path( __FILE__ ) . 'iframed-enqueue-block-assets/style.css' )
);
wp_add_inline_style( 'iframed-enqueue-block-assets', 'body{padding:20px!important}' );
wp_enqueue_script(
'iframed-enqueue-block-assets-script',
plugin_dir_url( __FILE__ ) . 'iframed-enqueue-block-assets/script.js',
array(),
filemtime( plugin_dir_path( __FILE__ ) . 'iframed-enqueue-block-assets/script.js' )
);
wp_localize_script(
'iframed-enqueue-block-assets-script',
'iframedEnqueueBlockAssetsL10n',
array(
'test' => 'Iframed Enqueue Block Assets!',
)
);
}
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
window.addEventListener( 'DOMContentLoaded', () => {
document.body.dataset.iframedEnqueueBlockAssetsL10n = window.iframedEnqueueBlockAssetsL10n.test;
} );
Loading