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

Block lazy loading #51778

Draft
wants to merge 3 commits into
base: trunk
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions docs/reference-guides/data/data-core-block-editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,10 @@ _Returns_

- `string|false`: Block Template Lock

### getUnsyncedPatterns

Undocumented declaration.

### hasBlockMovingClientId

Returns whether block moving mode is enabled.
Expand Down
8 changes: 8 additions & 0 deletions docs/reference-guides/data/data-core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,14 @@ _Returns_

- `(WPBlockVariation[]|void)`: Block variations.

### getBootstrappedBlockType

Undocumented declaration.

### getBootstrappedBlockTypes

Undocumented declaration.

### getCategories

Returns all the available block categories.
Expand Down
7 changes: 7 additions & 0 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,13 @@ function gutenberg_deregister_core_block_and_assets( $block_name ) {
}
}
}
if ( ! empty( $block_type->editor_script_handles ) ) {
foreach ( $block_type->editor_script_handles as $editor_script_handle ) {
if ( str_starts_with( $editor_script_handle, 'wp-block-' ) ) {
wp_deregister_script( $editor_script_handle );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To connect the efforts. I was looking in WordPress/wordpress-develop#5118 at ways to allow referencing the same file path by multiple blocks by storing a handle name in the asset file to use it as a way to prevent registering the same file under different names. As of today, WP core would register the same script file under different handles because the name is generated based on the block name.

}
}
}
$registry->unregister( $block_name );
}
}
Expand Down
52 changes: 52 additions & 0 deletions lib/init.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,55 @@
);
}
add_action( 'admin_menu', 'gutenberg_menu', 9 );

// disable loading and enqueuing block editor scripts and styles
add_filter( 'should_load_block_editor_scripts_and_styles', '__return_false', 11 );

function get_block_importmap() {

Check failure on line 64 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

The "get_block_importmap()" function should be guarded against redeclaration.
$block_registry = WP_Block_Type_Registry::get_instance();
$scripts = wp_scripts();

Check warning on line 66 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space
$styles = wp_styles();

Check warning on line 67 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Equals sign not aligned with surrounding assignments; expected 9 spaces but found 1 space
$blocks = array();

foreach ( $block_registry->get_all_registered() as $block_name => $block_type ) {
$imports = array();
if ( isset( $block_type->editor_script_handles ) ) {
foreach ( $block_type->editor_script_handles as $handle ) {
$spec = $scripts->registered[ $handle ];

Check warning on line 74 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space
$imports[] = array(
'type' => 'script',

Check warning on line 76 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Array double arrow not aligned correctly; expected 3 space(s) between "'type'" and double arrow, but found 1.
'handle' => $spec->handle,
'src' => $spec->src,

Check warning on line 78 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Array double arrow not aligned correctly; expected 4 space(s) between "'src'" and double arrow, but found 1.
'ver' => $spec->ver

Check warning on line 79 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Array double arrow not aligned correctly; expected 4 space(s) between "'ver'" and double arrow, but found 1.

Check failure on line 79 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

There should be a comma after the last array item in a multi-line array.
);
}
}
if ( isset( $block_type->editor_style_handles ) ) {
foreach ( $block_type->editor_style_handles as $handle ) {
if ( ! isset( $styles->registered[ $handle ] ) ) {
continue;
}
$spec = $styles->registered[ $handle ];

Check warning on line 88 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space
$imports[] = array(
'type' => 'style',

Check warning on line 90 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Array double arrow not aligned correctly; expected 3 space(s) between "'type'" and double arrow, but found 1.
'handle' => $spec->handle,
'src' => $spec->src,

Check warning on line 92 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Array double arrow not aligned correctly; expected 4 space(s) between "'src'" and double arrow, but found 1.
'ver' => $spec->ver

Check warning on line 93 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Array double arrow not aligned correctly; expected 4 space(s) between "'ver'" and double arrow, but found 1.

Check failure on line 93 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

There should be a comma after the last array item in a multi-line array.
);
}
}
if ( ! empty( $imports ) ) {
$blocks[ $block_name ] = $imports;
}
}

return $blocks;
}

function emit_importmap() {

Check failure on line 105 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

The "emit_importmap()" function should be guarded against redeclaration.
wp_register_script( 'wp-importmap', '');

Check failure on line 106 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Expected 1 spaces before closing parenthesis; 0 found
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we're calling wp_enqueue_script() down there, we don't need to register it at all. This line can be removed. We might only need to call the wp_add_inline_script() or wp_localize_script() after the wp_enqueue_script.

wp_add_inline_script( 'wp-importmap', 'wp.importmap = ' . wp_json_encode( get_block_importmap() ) . ';' );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wp_localize_script() could be an easier way to pass raw data from PHP to JS.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we aiming to use webpack and not native ES modules and import maps? I'd love to hear what your thoughts are about this choice.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, would love to understand why we're reinventing import maps?

wp_enqueue_script('wp-importmap');

Check failure on line 108 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Line indented incorrectly; expected at least 1 tabs, found 2 spaces

Check failure on line 108 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Expected 1 spaces after opening parenthesis; 0 found

Check failure on line 108 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Expected 1 spaces before closing parenthesis; 0 found
}

add_action( 'enqueue_block_editor_assets', 'emit_importmap' );

Check failure on line 111 in lib/init.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Expected 1 newline at end of file; 0 found
5 changes: 2 additions & 3 deletions packages/block-editor/src/autocompleters/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,20 +116,19 @@ function createBlockCompleter() {
allowContext( before, after ) {
return ! ( /\S/.test( before ) || /\S/.test( after ) );
},
getOptionCompletion( inserterItem ) {
async getOptionCompletion( inserterItem ) {
const {
name,
initialAttributes,
innerBlocks,
syncStatus,
content,
} = inserterItem;

return {
action: 'replace',
value:
syncStatus === 'unsynced'
? parse( content, {
? await parse( content, {
__unstableSkipMigrationLogs: true,
} )
: createBlock(
Expand Down
7 changes: 5 additions & 2 deletions packages/block-editor/src/components/block-actions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,18 @@ export default function BlockActions( {
selectBlock( clientIds[ 0 ] );
setBlockMovingClientId( clientIds[ 0 ] );
},
onGroup() {
async onGroup() {
if ( ! blocks.length ) {
return;
}

const groupingBlockName = getGroupingBlockName();

// Activate the `transform` on `core/group` which does the conversion.
const newBlocks = switchToBlockType( blocks, groupingBlockName );
const newBlocks = await switchToBlockType(
blocks,
groupingBlockName
);

if ( ! newBlocks ) {
return;
Expand Down
4 changes: 2 additions & 2 deletions packages/block-editor/src/components/block-list/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, registry ) => {
) {
removeBlock( _clientId );
} else {
registry.batch( () => {
registry.batch( async () => {
if (
canInsertBlockType(
getBlockName( firstClientId ),
Expand All @@ -321,7 +321,7 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, registry ) => {
getBlockIndex( _clientId )
);
} else {
const replacement = switchToBlockType(
const replacement = await switchToBlockType(
getBlock( firstClientId ),
getDefaultBlockName()
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, registry ) => {
) {
removeBlock( _clientId );
} else {
registry.batch( () => {
registry.batch( async () => {
if (
canInsertBlockType(
getBlockName( firstClientId ),
Expand All @@ -514,7 +514,7 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, registry ) => {
getBlockIndex( _clientId )
);
} else {
const replacement = switchToBlockType(
const replacement = await switchToBlockType(
getBlock( firstClientId ),
getDefaultBlockName()
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,13 @@ import { store as blockEditorStore } from '../../store';
*/
function useGenericPreviewBlock( block, type ) {
return useMemo( () => {
const example = type?.example;
const blockName = type?.name;

if ( example && blockName ) {
return getBlockFromExample( blockName, {
attributes: example.attributes,
innerBlocks: example.innerBlocks,
} );
if ( type && type.blockName && type.example ) {
return getBlockFromExample( type.blockName, type.example );
}

if ( block ) {
return cloneBlock( block );
}
}, [ type?.example ? block?.name : block, type ] );
}, [ type, type?.example ? block?.name : block ] );
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
getBlockMenuDefaultClassName,
switchToBlockType,
} from '@wordpress/blocks';
import { useState, useMemo } from '@wordpress/element';
import { useEffect, useState, useMemo } from '@wordpress/element';

/**
* Internal dependencies
Expand Down Expand Up @@ -63,6 +63,21 @@ function useGroupedTransforms( possibleBlockTransformations ) {
return transformations;
}

function Preview( { blocks, transformName } ) {
const [ switched, setSwitched ] = useState( null );
useEffect( () => {
switchToBlockType( blocks, transformName ).then( ( result ) =>
setSwitched( result )
);
}, [ blocks, transformName ] );

if ( ! switched ) {
return null;
}

return <PreviewBlockPopover blocks={ blocks } />;
}

const BlockTransformationsMenu = ( {
className,
possibleBlockTransformations,
Expand Down Expand Up @@ -91,11 +106,10 @@ const BlockTransformationsMenu = ( {
<>
<MenuGroup label={ __( 'Transform to' ) } className={ className }>
{ hoveredTransformItemName && (
<PreviewBlockPopover
blocks={ switchToBlockType(
blocks,
hoveredTransformItemName
) }
<Preview
key={ hoveredTransformItemName }
blocks={ blocks }
transformName={ hoveredTransformItemName }
/>
) }
{ !! possibleBlockVariationTransformations?.length && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ const BlockTransformationsMenu = ( {
const getAnchor = () =>
anchorNodeRef ? findNodeHandle( anchorNodeRef ) : undefined;

function onPickerSelect( value ) {
async function onPickerSelect( value ) {
replaceBlocks(
selectedBlockClientId,
switchToBlockType( selectedBlock, value )
await switchToBlockType( selectedBlock, value )
);

const selectedItem = pickerOptions().find(
Expand Down
Loading
Loading