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 Library: Unify handling for block view scripts #32814

Merged
merged 3 commits into from
Jun 23, 2021
Merged
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
42 changes: 34 additions & 8 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 ( ! wp_should_load_separate_core_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
aristath marked this conversation as resolved.
Show resolved Hide resolved
);
wp_style_add_data( "wp-block-{$block_name}", 'rtl', 'replace' );

Expand Down Expand Up @@ -227,7 +253,7 @@ function() {
"wp-block-{$block_name}",
gutenberg_url( $theme_style_path ),
array(),
filemtime( gutenberg_dir_path() . $theme_style_path )
$default_version
);
wp_style_add_data( "wp-block-{$block_name}", 'path', gutenberg_dir_path() . $theme_style_path );
}
Expand All @@ -240,7 +266,7 @@ function() {
"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
24 changes: 12 additions & 12 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 @@ -37,9 +37,9 @@ function render_my_block() {

function register_block_my_block() {
register_block_type(
__DIR__ . '/block-name',
__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
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 @@ -59,10 +55,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 @@ -150,16 +150,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
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,12 @@ exports[`ReadableJsAssetsWebpackPlugin should produce the expected output: Asset
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = \\"./frontend.js\\");
/******/ return __webpack_require__(__webpack_require__.s = \\"./index.js\\");
/******/ })
/************************************************************************/
/******/ ({

/***/ \\"./frontend.js\\":
/***/ \\"./index.js\\":
/***/ (function(module, exports) {

function notMinified() {}
Expand All @@ -101,7 +101,7 @@ notMinified();
/******/ });"
`;

exports[`ReadableJsAssetsWebpackPlugin should produce the expected output: Asset file should match snapshot 2`] = `"!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){\\"undefined\\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\\"Module\\"}),Object.defineProperty(e,\\"__esModule\\",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&\\"object\\"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,\\"default\\",{enumerable:!0,value:e}),2&t&&\\"string\\"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,\\"a\\",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=\\"\\",n(n.s=\\"./frontend.js\\")}({\\"./frontend.js\\":function(e,t){}});"`;
exports[`ReadableJsAssetsWebpackPlugin should produce the expected output: Asset file should match snapshot 2`] = `"!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){\\"undefined\\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\\"Module\\"}),Object.defineProperty(e,\\"__esModule\\",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&\\"object\\"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,\\"default\\",{enumerable:!0,value:e}),2&t&&\\"string\\"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,\\"a\\",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=\\"\\",n(n.s=\\"./index.js\\")}({\\"./index.js\\":function(e,t){}});"`;

exports[`ReadableJsAssetsWebpackPlugin should produce the expected output: Asset file should match snapshot 3`] = `
"/******/ (function(modules) { // webpackBootstrap
Expand Down Expand Up @@ -187,12 +187,12 @@ exports[`ReadableJsAssetsWebpackPlugin should produce the expected output: Asset
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = \\"./index.js\\");
/******/ return __webpack_require__(__webpack_require__.s = \\"./view.js\\");
/******/ })
/************************************************************************/
/******/ ({

/***/ \\"./index.js\\":
/***/ \\"./view.js\\":
/***/ (function(module, exports) {

function notMinified() {}
Expand All @@ -204,4 +204,4 @@ notMinified();
/******/ });"
`;

exports[`ReadableJsAssetsWebpackPlugin should produce the expected output: Asset file should match snapshot 4`] = `"!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){\\"undefined\\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\\"Module\\"}),Object.defineProperty(e,\\"__esModule\\",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&\\"object\\"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,\\"default\\",{enumerable:!0,value:e}),2&t&&\\"string\\"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,\\"a\\",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=\\"\\",n(n.s=\\"./index.js\\")}({\\"./index.js\\":function(e,t){}});"`;
exports[`ReadableJsAssetsWebpackPlugin should produce the expected output: Asset file should match snapshot 4`] = `"!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){\\"undefined\\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\\"Module\\"}),Object.defineProperty(e,\\"__esModule\\",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&\\"object\\"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,\\"default\\",{enumerable:!0,value:e}),2&t&&\\"string\\"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,\\"a\\",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p=\\"\\",r(r.s=\\"./view.js\\")}({\\"./view.js\\":function(e,t){}});"`;
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ module.exports = {
},
entry: {
index: './index.js',
frontend: './frontend.js',
view: './view.js',
},
output: {
filename: '[name].min.js',
Expand Down
37 changes: 20 additions & 17 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,34 +72,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 @@ -108,7 +111,7 @@ const createEntrypoints = () => {
};
}, {} );

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

module.exports = {
Expand Down Expand Up @@ -148,12 +151,12 @@ module.exports = {
// 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 files, they would be processed
// 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 ( request.includes( '/frontend.js' ) ) {
return `./build/block-library/blocks/[name]/frontend.min.js`;
if ( request.includes( '/view.js' ) ) {
return `./build/block-library/[name]/view.min.js`;
}

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