Cherry pick #378 into release/9.2 (#50801)

* use HTML API to inject attributes

* remove comment

* improve check

* Keep lower kebab-case conversion.

* Fix preventing double dash when an attrib starts with a uppercase letter.

* Removed unneeded var.

* Return early if $content does not start with <div to keep existing behaviour, and also keep the trim for output consistency.

* Revert to the return early based on WP_HTML_TAG_Processor::next_tag query

* Changed the early return condition.

* Added changelog.

* Remove changelog

---------

Co-authored-by: Luigi Teschio <gigitux@gmail.com>
Co-authored-by: Paulo Arromba <17236129+wavvves@users.noreply.github.com>
This commit is contained in:
Jorge A. Torres 2024-08-20 18:04:23 -03:00 committed by GitHub
parent 7f5b53afb4
commit 2cded2edb1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 25 additions and 11 deletions

View File

@ -227,20 +227,28 @@ final class BlockTypesController {
* @return string
*/
public function add_data_attributes( $content, $block ) {
$block_name = $block['blockName'];
if ( ! $this->block_should_have_data_attributes( $block_name ) ) {
$content = trim( $content );
if ( ! $this->block_should_have_data_attributes( $block['blockName'] ) ) {
return $content;
}
$attributes = (array) $block['attrs'];
$exclude_attributes = array( 'className', 'align' );
$escaped_data_attributes = array(
'data-block-name="' . esc_attr( $block['blockName'] ) . '"',
);
$attributes = (array) $block['attrs'];
$exclude_attributes = array( 'className', 'align' );
foreach ( $attributes as $key => $value ) {
if ( in_array( $key, $exclude_attributes, true ) ) {
$processor = new \WP_HTML_Tag_Processor( $content );
if (
false === $processor->next_token() ||
'DIV' !== $processor->get_token_name() ||
$processor->is_tag_closer()
) {
return $content;
}
foreach ( $attributes as $key => $value ) {
if ( ! is_string( $key ) || in_array( $key, $exclude_attributes, true ) ) {
continue;
}
if ( is_bool( $value ) ) {
@ -249,10 +257,16 @@ final class BlockTypesController {
if ( ! is_scalar( $value ) ) {
$value = wp_json_encode( $value );
}
$escaped_data_attributes[] = 'data-' . esc_attr( strtolower( preg_replace( '/(?<!\ )[A-Z]/', '-$0', $key ) ) ) . '="' . esc_attr( $value ) . '"';
// For output consistency, we convert camelCase to kebab-case and output in lowercase.
$key = strtolower( preg_replace( '/(?<!^|\ )[A-Z]/', '-$0', $key ) );
$processor->set_attribute( "data-{$key}", $value );
}
return preg_replace( '/^<div /', '<div ' . implode( ' ', $escaped_data_attributes ) . ' ', trim( $content ) );
// Set this last to prevent user-input from overriding it.
$processor->set_attribute( 'data-block-name', $block['blockName'] );
return $processor->get_updated_html();
}
/**