Skip to content

Commit

Permalink
Block Library: Unify handling for block view scripts (#32814)
Browse files Browse the repository at this point in the history
* Block Library: Unify handling for block view scripts

* Add logic that registers view scripts for blocks

* Fix e2e tests with view script for Navigation block
  • Loading branch information
gziolo authored and youknowriad committed Jun 24, 2021
1 parent 437ca8e commit 3ede3a2
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 70 deletions.
40 changes: 33 additions & 7 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ function gutenberg_reregister_core_block_types() {
$registry->unregister( $metadata['name'] );
}

gutenberg_register_core_block_styles( $folder_name );
gutenberg_register_core_block_assets( $folder_name );
register_block_type_from_metadata( $block_json_file );
}

Expand All @@ -147,7 +147,7 @@ function gutenberg_reregister_core_block_types() {
if ( $registry->is_registered( $block_name ) ) {
$registry->unregister( $block_name );
}
gutenberg_register_core_block_styles( $block_name );
gutenberg_register_core_block_assets( $block_name );
}

require_once $blocks_dir . $file;
Expand All @@ -164,13 +164,39 @@ function gutenberg_reregister_core_block_types() {
*
* @return void
*/
function gutenberg_register_core_block_styles( $block_name ) {
function gutenberg_register_core_block_assets( $block_name ) {
$block_name = str_replace( 'core/', '', $block_name );

// When in production, use the plugin's version as the default asset version;
// else (for development or test) default to use the current time.
$default_version = defined( 'GUTENBERG_VERSION' ) && ! ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? GUTENBERG_VERSION : time();
$script_suffix = '.min.js';

$view_script_path = "build/block-library/blocks/$block_name/view$script_suffix";
if ( file_exists( gutenberg_dir_path() . $view_script_path ) ) {
$view_script_handle = "wp-block-{$block_name}-view";
wp_deregister_script( $view_script_handle );

// Replace suffix and extension with `.asset.php` to find the generated dependencies file.
$view_asset_file = substr( $view_script_path, 0, -( strlen( $script_suffix ) ) ) . '.asset.php';
$view_asset = file_exists( gutenberg_dir_path() . $view_asset_file )
? require( gutenberg_dir_path() . $view_asset_file )
: null;
$view_script_dependencies = isset( $view_asset['dependencies'] ) ? $view_asset['dependencies'] : array();
$view_script_version = isset( $view_asset['version'] ) ? $view_asset['version'] : $default_version;

wp_register_script(
$view_script_handle,
gutenberg_url( $view_script_path ),
$view_script_dependencies,
$view_script_version
);
}

if ( ! gutenberg_should_load_separate_block_assets() ) {
return;
}

$block_name = str_replace( 'core/', '', $block_name );

$style_path = "build/block-library/blocks/$block_name/style.css";
$editor_style_path = "build/block-library/blocks/$block_name/style-editor.css";

Expand All @@ -180,7 +206,7 @@ function gutenberg_register_core_block_styles( $block_name ) {
"wp-block-{$block_name}",
gutenberg_url( $style_path ),
array(),
filemtime( gutenberg_dir_path() . $style_path )
$default_version
);
wp_style_add_data( "wp-block-{$block_name}", 'rtl', 'replace' );

Expand All @@ -196,7 +222,7 @@ function gutenberg_register_core_block_styles( $block_name ) {
"wp-block-{$block_name}-editor",
gutenberg_url( $editor_style_path ),
array(),
filemtime( gutenberg_dir_path() . $editor_style_path )
$default_version
);
wp_style_add_data( "wp-block-{$block_name}-editor", 'rtl', 'replace' );
} else {
Expand Down
26 changes: 13 additions & 13 deletions packages/block-library/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,20 @@ _This package assumes that your code will run in an **ES2015+** environment. If

## Building JavaScript for the browser

If a `frontend.js` file is present in the block's directory, this file will be built along other assets, making it available to load from the browser.
If a `view.js` file is present in the block's directory, this file will be built along other assets, making it available to load from the browser.

This enables us to, for instance, load this file when the block is present on the page in two ways:

1. Using the block's `render_callback`:

```php
function render_my_block() {
$script_path = __DIR__ . '/block-name/frontend.js';
function render_block_my_block() {
$script_path = __DIR__ . '/my-block/view.js';

if ( file_exists( $script_path ) ) {
wp_enqueue_script(
'my_block_frontend_script',
plugins_url( 'frontend.js', $script_path ),
'wp-block-my-block-view',
plugins_url( 'view.js', $script_path ),
array(),
false,
true
Expand All @@ -36,10 +36,10 @@ function render_my_block() {
}

function register_block_my_block() {
register_block_type_from_metadata(
__DIR__ . '/block-name',
register_block_type(
__DIR__ . '/my-block',
array(
'render_callback' => 'render_my_block',
'render_callback' => 'render_block_my_block',
)
);
}
Expand All @@ -51,21 +51,21 @@ add_action( 'init', 'register_block_my_block' );
2. Using the `render_block` filter:

```php
function render_my_block() {
$script_path = __DIR__ . '/block-name/frontend.js';
function render_block_my_block() {
$script_path = __DIR__ . '/my-block/view.js';

if ( file_exists( $script_path ) ) {
wp_enqueue_script(
'my_block_frontend_script',
plugins_url( 'frontend.js', $script_path ),
'wp-block-my-block-view',
plugins_url( 'view.js', $script_path ),
array(),
false,
true
);
}
}

apply_filter( 'render_block', 'render_my_block' );
apply_filter( 'render_block', 'render_block_my_block' );
```

## API
Expand Down
10 changes: 4 additions & 6 deletions packages/block-library/src/file/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@
*/

/**
* When the `core/file` block is rendering, check if we need to enqueue the `'wp-block-library-file` script.
* When the `core/file` block is rendering, check if we need to enqueue the `'wp-block-file-view` script.
*
* @param array $attributes The block attributes.
* @param array $content The block content.
*
* @return string Returns the block content.
*/
function render_block_core_file( $attributes, $content ) {
if ( ! empty( $attributes['displayPreview'] ) ) {
// Check if it's already enqueued, so we don't add the inline script multiple times.
if ( ! wp_script_is( 'wp-block-library-file' ) ) {
wp_enqueue_script( 'wp-block-library-file', plugins_url( 'file/frontend.js', __FILE__ ) );
}
$should_load_view_script = ! empty( $attributes['displayPreview'] ) && ! wp_script_is( 'wp-block-file-view' );
if ( $should_load_view_script ) {
wp_enqueue_script( 'wp-block-file-view' );
}

return $content;
Expand Down
File renamed without changes.
11 changes: 2 additions & 9 deletions packages/block-library/src/navigation/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@
"title": "Navigation",
"category": "theme",
"description": "A collection of blocks that allow visitors to get around your site.",
"keywords": [
"menu",
"navigation",
"links"
],
"keywords": [ "menu", "navigation", "links" ],
"textdomain": "default",
"attributes": {
"orientation": {
Expand Down Expand Up @@ -56,10 +52,7 @@
"orientation": "orientation"
},
"supports": {
"align": [
"wide",
"full"
],
"align": [ "wide", "full" ],
"anchor": true,
"html": false,
"inserter": true,
Expand Down
14 changes: 4 additions & 10 deletions packages/block-library/src/navigation/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,16 +120,10 @@ function render_block_core_navigation( $attributes, $content, $block ) {
}

unset( $attributes['rgbTextColor'], $attributes['rgbBackgroundColor'] );
$should_load_frontend_script = $attributes['isResponsive'] && ! wp_script_is( 'core_block_navigation_load_frontend_scripts' );

if ( $should_load_frontend_script ) {
wp_enqueue_script(
'core_block_navigation_load_frontend_scripts',
plugins_url( 'frontend.js', __DIR__ . '/navigation/frontend.js' ),
array(),
false,
true
);

$should_load_view_script = ! empty( $attributes['isResponsive'] ) && ! wp_script_is( 'wp-block-navigation-view' );
if ( $should_load_view_script ) {
wp_enqueue_script( 'wp-block-navigation-view' );
}

if ( empty( $block->inner_blocks ) ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ describe( 'Navigation', () => {
() =>
null !==
document.querySelector(
'script[src*="navigation/frontend.js"]'
'script[src*="navigation/view.min.js"]'
)
);

Expand All @@ -582,7 +582,7 @@ describe( 'Navigation', () => {
() =>
Array.from(
document.querySelectorAll(
'script[src*="navigation/frontend.js"]'
'script[src*="navigation/view.min.js"]'
)
).length
);
Expand Down Expand Up @@ -614,7 +614,7 @@ describe( 'Navigation', () => {
() =>
null !==
document.querySelector(
'script[src*="navigation/frontend.js"]'
'script[src*="navigation/view.min.js"]'
)
);

Expand All @@ -632,7 +632,7 @@ describe( 'Navigation', () => {
() =>
null !==
document.querySelector(
'script[src*="navigation/frontend.js"]'
'script[src*="navigation/view.min.js"]'
)
);

Expand Down
48 changes: 27 additions & 21 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,34 +67,37 @@ const stylesTransform = ( content ) => {

/*
* Matches a block's name in paths in the form
* build-module/<blockName>/frontend.js
* build-module/<blockName>/view.js
*/
const blockNameRegex = new RegExp( /(?<=build-module\/).*(?=(\/frontend))/g );
const blockNameRegex = new RegExp( /(?<=build-module\/).*(?=(\/view))/g );

const createEntrypoints = () => {
/*
* Returns an array of paths to frontend.js files within the block-directory package.
* Returns an array of paths to view.js files within the `@wordpress/block-library` package.
* These paths can be matched by the regex `blockNameRegex` in order to extract
* the block's name.
*
* Returns an empty array if no files were found.
*/
const scriptPaths = fastGlob.sync(
'./packages/block-library/build-module/**/frontend.js'
const blockViewScriptPaths = fastGlob.sync(
'./packages/block-library/build-module/**/view.js'
);

/*
* Go through the paths found above, in order to define webpack entry points for
* each block's frontend.js file.
* each block's view.js file.
*/
const scriptEntries = scriptPaths.reduce( ( entries, scriptPath ) => {
const [ blockName ] = scriptPath.match( blockNameRegex );
const blockViewScriptEntries = blockViewScriptPaths.reduce(
( entries, scriptPath ) => {
const [ blockName ] = scriptPath.match( blockNameRegex );

return {
...entries,
[ blockName ]: scriptPath,
};
}, {} );
return {
...entries,
[ 'blocks/' + blockName ]: scriptPath,
};
},
{}
);

const packageEntries = gutenbergPackages.reduce( ( memo, packageName ) => {
return {
Expand All @@ -103,7 +106,7 @@ const createEntrypoints = () => {
};
}, {} );

return { ...packageEntries, ...scriptEntries };
return { ...packageEntries, ...blockViewScriptEntries };
};

module.exports = {
Expand Down Expand Up @@ -138,14 +141,17 @@ module.exports = {
filename: ( data ) => {
const { chunk } = data;
const { entryModule } = chunk;
const { rawRequest } = entryModule;
const { rawRequest, rootModule } = entryModule;

// When processing ESM files, the requested path
// is defined in `entryModule.rootModule.rawRequest`, instead of
// being present in `entryModule.rawRequest`.
// In the context of frontend view files, they would be processed
// as ESM if they use `import` or `export` within it.
const request = rootModule?.rawRequest || rawRequest;

/*
* If the file being built is a Core Block's frontend file,
* we build it in the block's directory.
*/
if ( rawRequest && rawRequest.includes( '/frontend.js' ) ) {
return `./build/block-library/blocks/[name]/frontend.js`;
if ( request.includes( '/view.js' ) ) {
return `./build/block-library/[name]/view.min.js`;
}

return './build/[name]/index.js';
Expand Down

0 comments on commit 3ede3a2

Please sign in to comment.