Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Block Library: Unify handling for block view scripts
  • Loading branch information
gziolo committed Jun 22, 2021
commit 1ae6b28132fb88405e21a5d2c061aea9eea3fd93
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
14 changes: 4 additions & 10 deletions packages/e2e-tests/specs/experiments/blocks/navigation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -558,9 +558,7 @@ describe( 'Navigation', () => {
const isScriptLoaded = await previewPage.evaluate(
() =>
null !==
document.querySelector(
'script[src*="navigation/frontend.js"]'
)
document.querySelector( 'script[src*="navigation/view.js"]' )
);

expect( isScriptLoaded ).toBe( false );
Expand All @@ -582,7 +580,7 @@ describe( 'Navigation', () => {
() =>
Array.from(
document.querySelectorAll(
'script[src*="navigation/frontend.js"]'
'script[src*="navigation/view.js"]'
)
).length
);
Expand Down Expand Up @@ -613,9 +611,7 @@ describe( 'Navigation', () => {
let isScriptLoaded = await previewPage.evaluate(
() =>
null !==
document.querySelector(
'script[src*="navigation/frontend.js"]'
)
document.querySelector( 'script[src*="navigation/view.js"]' )
);

expect( isScriptLoaded ).toBe( false );
Expand All @@ -631,9 +627,7 @@ describe( 'Navigation', () => {
isScriptLoaded = await previewPage.evaluate(
() =>
null !==
document.querySelector(
'script[src*="navigation/frontend.js"]'
)
document.querySelector( 'script[src*="navigation/view"]' )
);

expect( isScriptLoaded ).toBe( true );
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