Skip to content

Commit

Permalink
Build: Stop generating unused legacy scripts for core blocks (#65268)
Browse files Browse the repository at this point in the history
* Build: Stop generating unused legacy scripts for core blocks

* Refactor Form block to use view script module

Co-authored-by: gziolo <[email protected]>
Co-authored-by: sirreal <[email protected]>
  • Loading branch information
3 people authored Dec 6, 2024
1 parent 15bff41 commit 9e76f0f
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 69 deletions.
19 changes: 19 additions & 0 deletions lib/experimental/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,22 @@ function gutenberg_register_block_style( $block_name, $style_properties ) {

return $result;
}

/**
* Additional data to expose to the view script module in the Form block.
*/
function gutenberg_block_core_form_view_script_module( $data ) {
if ( ! gutenberg_is_experiment_enabled( 'gutenberg-form-blocks' ) ) {
return $data;
}

$data['nonce'] = wp_create_nonce( 'wp-block-form' );
$data['ajaxUrl'] = admin_url( 'admin-ajax.php' );
$data['action'] = 'wp_block_form_email_submit';

return $data;
}
add_filter(
'script_module_data_@wordpress/block-library/form/view',
'gutenberg_block_core_form_view_script_module'
);
1 change: 1 addition & 0 deletions packages/block-library/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"wpScript": true,
"wpScriptModuleExports": {
"./file/view": "./build-module/file/view.js",
"./form/view": "./build-module/form/view.js",
"./image/view": "./build-module/image/view.js",
"./navigation/view": "./build-module/navigation/view.js",
"./query/view": "./build-module/query/view.js",
Expand Down
3 changes: 1 addition & 2 deletions packages/block-library/src/form/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,5 @@
}
},
"__experimentalSelector": "form"
},
"viewScript": "file:./view.min.js"
}
}
21 changes: 1 addition & 20 deletions packages/block-library/src/form/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* @return string The content of the block being rendered.
*/
function render_block_core_form( $attributes, $content ) {
wp_enqueue_script_module( '@wordpress/block-library/form/view' );

$processed_content = new WP_HTML_Tag_Processor( $content );
$processed_content->next_tag( 'form' );
Expand Down Expand Up @@ -42,26 +43,6 @@ function render_block_core_form( $attributes, $content ) {
);
}

/**
* Additional data to add to the view.js script for this block.
*/
function block_core_form_view_script() {
if ( ! gutenberg_is_experiment_enabled( 'gutenberg-form-blocks' ) ) {
return;
}

wp_localize_script(
'wp-block-form-view',
'wpBlockFormSettings',
array(
'nonce' => wp_create_nonce( 'wp-block-form' ),
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'action' => 'wp_block_form_email_submit',
)
);
}
add_action( 'wp_enqueue_scripts', 'block_core_form_view_script' );

/**
* Adds extra fields to the form.
*
Expand Down
23 changes: 18 additions & 5 deletions packages/block-library/src/form/view.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
let formSettings;
try {
formSettings = JSON.parse(
document.getElementById(
'wp-script-module-data-@wordpress/block-library/form/view'
)?.textContent
);
} catch {}

// eslint-disable-next-line eslint-comments/disable-enable-pair
/* eslint-disable no-undef */
document.querySelectorAll( 'form.wp-block-form' ).forEach( function ( form ) {
// Bail If the form is not using the mailto: action.
if ( ! form.action || ! form.action.startsWith( 'mailto:' ) ) {
// Bail If the form settings not provided or the form is not using the mailto: action.
if (
! formSettings ||
! form.action ||
! form.action.startsWith( 'mailto:' )
) {
return;
}

Expand All @@ -18,13 +31,13 @@ document.querySelectorAll( 'form.wp-block-form' ).forEach( function ( form ) {
// Get the form data and merge it with the form action and nonce.
const formData = Object.fromEntries( new FormData( form ).entries() );
formData.formAction = form.action;
formData._ajax_nonce = wpBlockFormSettings.nonce;
formData.action = wpBlockFormSettings.action;
formData._ajax_nonce = formSettings.nonce;
formData.action = formSettings.action;
formData._wp_http_referer = window.location.href;
formData.formAction = form.action;

try {
const response = await fetch( wpBlockFormSettings.ajaxUrl, {
const response = await fetch( formSettings.ajaxUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Expand Down
43 changes: 1 addition & 42 deletions tools/webpack/blocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,18 @@
*/
const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
const { join, sep, basename } = require( 'path' );
const fastGlob = require( 'fast-glob' );
const { realpathSync } = require( 'fs' );

/**
* WordPress dependencies
*/
const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );
const { PhpFilePathsPlugin } = require( '@wordpress/scripts/utils' );

/**
* Internal dependencies
*/
const { baseConfig, plugins, stylesTransform } = require( './shared' );

/*
* Matches a block's filepaths in the form build-module/<filename>.js
*/
const blockViewRegex = new RegExp(
/build-module\/(?<filename>.*\/view.*).js$/
);

/**
* We need to automatically rename some functions when they are called inside block files,
* but have been declared elsewhere. This way we can call Gutenberg override functions, but
Expand All @@ -50,48 +41,16 @@ function escapeRegExp( string ) {
return string.replace( /[\\^$.*+?()[\]{}|]/g, '\\$&' );
}

const createEntrypoints = () => {
/*
* Returns an array of paths to block view files within the `@wordpress/block-library` package.
* These paths can be matched by the regex `blockViewRegex` in order to extract
* the block's filename. All blocks were migrated to script modules but the Form block.
*
* Returns an empty array if no files were found.
*/
const blockViewScriptPaths = fastGlob.sync(
'./packages/block-library/build-module/form/view.js'
);

/*
* Go through the paths found above, in order to define webpack entry points for
* each block's view.js file.
*/
return blockViewScriptPaths.reduce( ( entries, scriptPath ) => {
const result = scriptPath.match( blockViewRegex );
if ( ! result?.groups?.filename ) {
return entries;
}

return {
...entries,
[ result.groups.filename ]: scriptPath,
};
}, {} );
};

module.exports = [
{
...baseConfig,
name: 'blocks',
entry: createEntrypoints(),
entry: {},
output: {
devtoolNamespace: 'wp',
filename: './build/block-library/blocks/[name].min.js',
path: join( __dirname, '..', '..' ),
},
plugins: [
...plugins,
new DependencyExtractionWebpackPlugin( { injectPolyfill: false } ),
new PhpFilePathsPlugin( {
context: './packages/block-library/src/',
props: [ 'render', 'variations' ],
Expand Down

1 comment on commit 9e76f0f

@github-actions
Copy link

Choose a reason for hiding this comment

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

Flaky tests detected in 9e76f0f.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/12195359773
📝 Reported issues:

Please sign in to comment.